
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>QuerySet API reference &#8212; Django 1.11.22.dev20190603194737 documentation</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Lookup API reference" href="lookups.html" />
    <link rel="prev" title="Model instance reference" href="instances.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.11.22.dev20190603194737 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="instances.html" title="Model instance reference">previous</a>
     |
    <a href="../index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="lookups.html" title="Lookup API reference">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-models-querysets">
            
  <div class="section" id="s-queryset-api-reference">
<span id="queryset-api-reference"></span><h1><code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> API reference<a class="headerlink" href="#queryset-api-reference" title="Permalink to this headline">¶</a></h1>
<p>This document describes the details of the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> API. It builds on the
material presented in the <a class="reference internal" href="../../topics/db/models.html"><span class="doc">model</span></a> and <a class="reference internal" href="../../topics/db/queries.html"><span class="doc">database
query</span></a> guides, so you’ll probably want to read and
understand those documents before reading this one.</p>
<p>Throughout this reference we’ll use the <a class="reference internal" href="../../topics/db/queries.html#queryset-model-example"><span class="std std-ref">example Weblog models</span></a> presented in the <a class="reference internal" href="../../topics/db/queries.html"><span class="doc">database query guide</span></a>.</p>
<div class="section" id="s-when-querysets-are-evaluated">
<span id="s-id1"></span><span id="when-querysets-are-evaluated"></span><span id="id1"></span><h2>When <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s are evaluated<a class="headerlink" href="#when-querysets-are-evaluated" title="Permalink to this headline">¶</a></h2>
<p>Internally, a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> can be constructed, filtered, sliced, and generally
passed around without actually hitting the database. No database activity
actually occurs until you do something to evaluate the queryset.</p>
<p>You can evaluate a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> in the following ways:</p>
<ul>
<li><p class="first"><strong>Iteration.</strong> A <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> is iterable, and it executes its database
query the first time you iterate over it. For example, this will print
the headline of all entries in the database:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">headline</span><span class="p">)</span>
</pre></div>
</div>
<p>Note: Don’t use this if all you want to do is determine if at least one
result exists. It’s more efficient to use <a class="reference internal" href="#django.db.models.query.QuerySet.exists" title="django.db.models.query.QuerySet.exists"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exists()</span></code></a>.</p>
</li>
<li><p class="first"><strong>Slicing.</strong> As explained in <a class="reference internal" href="../../topics/db/queries.html#limiting-querysets"><span class="std std-ref">Limiting QuerySets</span></a>, a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> can
be sliced, using Python’s array-slicing syntax. Slicing an unevaluated
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> usually returns another unevaluated <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>, but Django
will execute the database query if you use the “step” parameter of slice
syntax, and will return a list. Slicing a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> that has been
evaluated also returns a list.</p>
<p>Also note that even though slicing an unevaluated <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> returns
another unevaluated <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>, modifying it further (e.g., adding
more filters, or modifying ordering) is not allowed, since that does not
translate well into SQL and it would not have a clear meaning either.</p>
</li>
<li><p class="first"><strong>Pickling/Caching.</strong> See the following section for details of what
is involved when <a class="reference internal" href="#pickling-querysets">pickling QuerySets</a>. The important thing for the
purposes of this section is that the results are read from the database.</p>
</li>
<li><p class="first"><strong>repr().</strong> A <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> is evaluated when you call <code class="docutils literal notranslate"><span class="pre">repr()</span></code> on it.
This is for convenience in the Python interactive interpreter, so you can
immediately see your results when using the API interactively.</p>
</li>
<li><p class="first"><strong>len().</strong> A <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> is evaluated when you call <code class="docutils literal notranslate"><span class="pre">len()</span></code> on it.
This, as you might expect, returns the length of the result list.</p>
<p>Note: If you only need to determine the number of records in the set (and
don’t need the actual objects), it’s much more efficient to handle a count
at the database level using SQL’s <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">COUNT(*)</span></code>. Django provides a
<a class="reference internal" href="#django.db.models.query.QuerySet.count" title="django.db.models.query.QuerySet.count"><code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code></a> method for precisely this reason.</p>
</li>
<li><p class="first"><strong>list().</strong> Force evaluation of a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> by calling <code class="docutils literal notranslate"><span class="pre">list()</span></code> on
it. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">entry_list</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">())</span>
</pre></div>
</div>
</li>
<li><p class="first"><strong>bool().</strong> Testing a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> in a boolean context, such as using
<code class="docutils literal notranslate"><span class="pre">bool()</span></code>, <code class="docutils literal notranslate"><span class="pre">or</span></code>, <code class="docutils literal notranslate"><span class="pre">and</span></code> or an <code class="docutils literal notranslate"><span class="pre">if</span></code> statement, will cause the query
to be executed. If there is at least one result, the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> is
<code class="docutils literal notranslate"><span class="pre">True</span></code>, otherwise <code class="docutils literal notranslate"><span class="pre">False</span></code>. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s2">&quot;Test&quot;</span><span class="p">):</span>
   <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;There is at least one Entry with the headline Test&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note: If you only want to determine if at least one result exists (and don’t
need the actual objects), it’s more efficient to use <a class="reference internal" href="#django.db.models.query.QuerySet.exists" title="django.db.models.query.QuerySet.exists"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exists()</span></code></a>.</p>
</li>
</ul>
<div class="section" id="s-pickling-querysets">
<span id="s-id2"></span><span id="pickling-querysets"></span><span id="id2"></span><h3>Pickling <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s<a class="headerlink" href="#pickling-querysets" title="Permalink to this headline">¶</a></h3>
<p>If you <a class="reference external" href="https://docs.python.org/3/library/pickle.html#module-pickle" title="(in Python v3.7)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>, this will force all the results to be loaded
into memory prior to pickling. Pickling is usually used as a precursor to
caching and when the cached queryset is reloaded, you want the results to
already be present and ready for use (reading from the database can take some
time, defeating the purpose of caching). This means that when you unpickle a
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>, it contains the results at the moment it was pickled, rather
than the results that are currently in the database.</p>
<p>If you only want to pickle the necessary information to recreate the
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> from the database at a later time, pickle the <code class="docutils literal notranslate"><span class="pre">query</span></code> attribute
of the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>. You can then recreate the original <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> (without
any results loaded) using some code like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pickle</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">query</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>     <span class="c1"># Assuming &#39;s&#39; is the pickled string.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">qs</span> <span class="o">=</span> <span class="n">MyModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">qs</span><span class="o">.</span><span class="n">query</span> <span class="o">=</span> <span class="n">query</span>            <span class="c1"># Restore the original &#39;query&#39;.</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">query</span></code> attribute is an opaque object. It represents the internals of
the query construction and is not part of the public API. However, it is safe
(and fully supported) to pickle and unpickle the attribute’s contents as
described here.</p>
<div class="admonition-you-can-t-share-pickles-between-versions admonition">
<p class="first admonition-title">You can’t share pickles between versions</p>
<p>Pickles of <code class="docutils literal notranslate"><span class="pre">QuerySets</span></code> are only valid for the version of Django that
was used to generate them. If you generate a pickle using Django
version N, there is no guarantee that pickle will be readable with
Django version N+1. Pickles should not be used as part of a long-term
archival strategy.</p>
<p class="last">Since pickle compatibility errors can be difficult to diagnose, such as
silently corrupted objects, a <code class="docutils literal notranslate"><span class="pre">RuntimeWarning</span></code> is raised when you try to
unpickle a queryset in a Django version that is different than the one in
which it was pickled.</p>
</div>
</div>
</div>
<div class="section" id="s-queryset-api">
<span id="s-id3"></span><span id="queryset-api"></span><span id="id3"></span><h2><code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> API<a class="headerlink" href="#queryset-api" title="Permalink to this headline">¶</a></h2>
<p>Here’s the formal declaration of a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>:</p>
<dl class="class">
<dt id="django.db.models.query.QuerySet">
<em class="property">class </em><code class="descname">QuerySet</code>(<em>model=None</em>, <em>query=None</em>, <em>using=None</em>)<a class="reference internal" href="../../_modules/django/db/models/query.html#QuerySet"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.query.QuerySet" title="Permalink to this definition">¶</a></dt>
<dd><p>Usually when you’ll interact with a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> you’ll use it by
<a class="reference internal" href="../../topics/db/queries.html#chaining-filters"><span class="std std-ref">chaining filters</span></a>. To make this work, most
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> methods return new querysets. These methods are covered in
detail later in this section.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> class has two public attributes you can use for
introspection:</p>
<dl class="attribute">
<dt id="django.db.models.query.QuerySet.ordered">
<code class="descname">ordered</code><a class="headerlink" href="#django.db.models.query.QuerySet.ordered" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">True</span></code> if the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> is ordered — i.e. has an
<a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><code class="xref py py-meth docutils literal notranslate"><span class="pre">order_by()</span></code></a> clause or a default ordering on the model.
<code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.query.QuerySet.db">
<code class="descname">db</code><a class="headerlink" href="#django.db.models.query.QuerySet.db" title="Permalink to this definition">¶</a></dt>
<dd><p>The database that will be used if this query is executed now.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <code class="docutils literal notranslate"><span class="pre">query</span></code> parameter to <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> exists so that specialized
query subclasses such as
<a class="reference internal" href="../contrib/gis/geoquerysets.html#django.contrib.gis.db.models.GeoQuerySet" title="django.contrib.gis.db.models.GeoQuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">GeoQuerySet</span></code></a> can reconstruct
internal query state. The value of the parameter is an opaque
representation of that query state and is not part of a public API.
To put it simply: if you need to ask, you don’t need to use it.</p>
</div>
</dd></dl>

<div class="section" id="s-methods-that-return-new-querysets">
<span id="methods-that-return-new-querysets"></span><h3>Methods that return new <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s<a class="headerlink" href="#methods-that-return-new-querysets" title="Permalink to this headline">¶</a></h3>
<p>Django provides a range of <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> refinement methods that modify either
the types of results returned by the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> or the way its SQL query is
executed.</p>
<div class="section" id="s-filter">
<span id="filter"></span><h4><code class="docutils literal notranslate"><span class="pre">filter()</span></code><a class="headerlink" href="#filter" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.filter">
<code class="descname">filter</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.filter" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a new <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> containing objects that match the given lookup
parameters.</p>
<p>The lookup parameters (<code class="docutils literal notranslate"><span class="pre">**kwargs</span></code>) should be in the format described in
<a class="reference internal" href="#id4">Field lookups</a> below. Multiple parameters are joined via <code class="docutils literal notranslate"><span class="pre">AND</span></code> in the
underlying SQL statement.</p>
<p>If you need to execute more complex queries (for example, queries with <code class="docutils literal notranslate"><span class="pre">OR</span></code> statements),
you can use <a class="reference internal" href="#django.db.models.Q" title="django.db.models.Q"><code class="xref py py-class docutils literal notranslate"><span class="pre">Q</span> <span class="pre">objects</span></code></a>.</p>
</div>
<div class="section" id="s-exclude">
<span id="exclude"></span><h4><code class="docutils literal notranslate"><span class="pre">exclude()</span></code><a class="headerlink" href="#exclude" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.exclude">
<code class="descname">exclude</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.exclude" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a new <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> containing objects that do <em>not</em> match the given
lookup parameters.</p>
<p>The lookup parameters (<code class="docutils literal notranslate"><span class="pre">**kwargs</span></code>) should be in the format described in
<a class="reference internal" href="#id4">Field lookups</a> below. Multiple parameters are joined via <code class="docutils literal notranslate"><span class="pre">AND</span></code> in the
underlying SQL statement, and the whole thing is enclosed in a <code class="docutils literal notranslate"><span class="pre">NOT()</span></code>.</p>
<p>This example excludes all entries whose <code class="docutils literal notranslate"><span class="pre">pub_date</span></code> is later than 2005-1-3
AND whose <code class="docutils literal notranslate"><span class="pre">headline</span></code> is “Hello”:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">pub_date__gt</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="n">headline</span><span class="o">=</span><span class="s1">&#39;Hello&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>In SQL terms, that evaluates to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span>
<span class="n">WHERE</span> <span class="n">NOT</span> <span class="p">(</span><span class="n">pub_date</span> <span class="o">&gt;</span> <span class="s1">&#39;2005-1-3&#39;</span> <span class="n">AND</span> <span class="n">headline</span> <span class="o">=</span> <span class="s1">&#39;Hello&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This example excludes all entries whose <code class="docutils literal notranslate"><span class="pre">pub_date</span></code> is later than 2005-1-3
OR whose headline is “Hello”:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">pub_date__gt</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s1">&#39;Hello&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>In SQL terms, that evaluates to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span>
<span class="n">WHERE</span> <span class="n">NOT</span> <span class="n">pub_date</span> <span class="o">&gt;</span> <span class="s1">&#39;2005-1-3&#39;</span>
<span class="n">AND</span> <span class="n">NOT</span> <span class="n">headline</span> <span class="o">=</span> <span class="s1">&#39;Hello&#39;</span>
</pre></div>
</div>
<p>Note the second example is more restrictive.</p>
<p>If you need to execute more complex queries (for example, queries with <code class="docutils literal notranslate"><span class="pre">OR</span></code> statements),
you can use <a class="reference internal" href="#django.db.models.Q" title="django.db.models.Q"><code class="xref py py-class docutils literal notranslate"><span class="pre">Q</span> <span class="pre">objects</span></code></a>.</p>
</div>
<div class="section" id="s-annotate">
<span id="annotate"></span><h4><code class="docutils literal notranslate"><span class="pre">annotate()</span></code><a class="headerlink" href="#annotate" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.annotate">
<code class="descname">annotate</code>(<em>*args</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.annotate" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Annotates each object in the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> with the provided list of <a class="reference internal" href="expressions.html"><span class="doc">query
expressions</span></a>. An expression may be a simple value, a
reference to a field on the model (or any related models), or an aggregate
expression (averages, sums, etc.) that has been computed over the objects that
are related to the objects in the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>.</p>
<p>Each argument to <code class="docutils literal notranslate"><span class="pre">annotate()</span></code> is an annotation that will be added
to each object in the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> that is returned.</p>
<p>The aggregation functions that are provided by Django are described
in <a class="reference internal" href="#id5">Aggregation Functions</a> below.</p>
<p>Annotations specified using keyword arguments will use the keyword as
the alias for the annotation. Anonymous arguments will have an alias
generated for them based upon the name of the aggregate function and
the model field that is being aggregated. Only aggregate expressions
that reference a single field can be anonymous arguments. Everything
else must be a keyword argument.</p>
<p>For example, if you were manipulating a list of blogs, you may want
to determine how many entries have been made in each blog:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="k">import</span> <span class="n">Count</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span><span class="n">Count</span><span class="p">(</span><span class="s1">&#39;entry&#39;</span><span class="p">))</span>
<span class="go"># The name of the first blog</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">name</span>
<span class="go">&#39;Blogasaurus&#39;</span>
<span class="go"># The number of entries on the first blog</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">entry__count</span>
<span class="go">42</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">Blog</span></code> model doesn’t define an <code class="docutils literal notranslate"><span class="pre">entry__count</span></code> attribute by itself,
but by using a keyword argument to specify the aggregate function, you can
control the name of the annotation:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span><span class="n">number_of_entries</span><span class="o">=</span><span class="n">Count</span><span class="p">(</span><span class="s1">&#39;entry&#39;</span><span class="p">))</span>
<span class="go"># The number of entries on the first blog, using the name provided</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">number_of_entries</span>
<span class="go">42</span>
</pre></div>
</div>
<p>For an in-depth discussion of aggregation, see <a class="reference internal" href="../../topics/db/aggregation.html"><span class="doc">the topic guide on
Aggregation</span></a>.</p>
</div>
<div class="section" id="s-order-by">
<span id="order-by"></span><h4><code class="docutils literal notranslate"><span class="pre">order_by()</span></code><a class="headerlink" href="#order-by" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.order_by">
<code class="descname">order_by</code>(<em>*fields</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.order_by" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>By default, results returned by a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> are ordered by the ordering
tuple given by the <code class="docutils literal notranslate"><span class="pre">ordering</span></code> option in the model’s <code class="docutils literal notranslate"><span class="pre">Meta</span></code>. You can
override this on a per-<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> basis by using the <code class="docutils literal notranslate"><span class="pre">order_by</span></code> method.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2005</span><span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;-pub_date&#39;</span><span class="p">,</span> <span class="s1">&#39;headline&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The result above will be ordered by <code class="docutils literal notranslate"><span class="pre">pub_date</span></code> descending, then by
<code class="docutils literal notranslate"><span class="pre">headline</span></code> ascending. The negative sign in front of <code class="docutils literal notranslate"><span class="pre">&quot;-pub_date&quot;</span></code> indicates
<em>descending</em> order. Ascending order is implied. To order randomly, use <code class="docutils literal notranslate"><span class="pre">&quot;?&quot;</span></code>,
like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;?&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note: <code class="docutils literal notranslate"><span class="pre">order_by('?')</span></code> queries may be expensive and slow, depending on the
database backend you’re using.</p>
<p>To order by a field in a different model, use the same syntax as when you are
querying across model relations. That is, the name of the field, followed by a
double underscore (<code class="docutils literal notranslate"><span class="pre">__</span></code>), followed by the name of the field in the new model,
and so on for as many models as you want to join. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;blog__name&#39;</span><span class="p">,</span> <span class="s1">&#39;headline&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you try to order by a field that is a relation to another model, Django will
use the default ordering on the related model, or order by the related model’s
primary key if there is no <a class="reference internal" href="options.html#django.db.models.Options.ordering" title="django.db.models.Options.ordering"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Meta.ordering</span></code></a> specified. For example, since the <code class="docutils literal notranslate"><span class="pre">Blog</span></code>
model has no default ordering specified:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;blog&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>…is identical to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;blog__id&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If <code class="docutils literal notranslate"><span class="pre">Blog</span></code> had <code class="docutils literal notranslate"><span class="pre">ordering</span> <span class="pre">=</span> <span class="pre">['name']</span></code>, then the first queryset would be
identical to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;blog__name&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>You can also order by <a class="reference internal" href="expressions.html"><span class="doc">query expressions</span></a> by
calling <code class="docutils literal notranslate"><span class="pre">asc()</span></code> or <code class="docutils literal notranslate"><span class="pre">desc()</span></code> on the expression:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="n">Coalesce</span><span class="p">(</span><span class="s1">&#39;summary&#39;</span><span class="p">,</span> <span class="s1">&#39;headline&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">desc</span><span class="p">())</span>
</pre></div>
</div>
<p>Be cautious when ordering by fields in related models if you are also using
<a class="reference internal" href="#django.db.models.query.QuerySet.distinct" title="django.db.models.query.QuerySet.distinct"><code class="xref py py-meth docutils literal notranslate"><span class="pre">distinct()</span></code></a>. See the note in <a class="reference internal" href="#django.db.models.query.QuerySet.distinct" title="django.db.models.query.QuerySet.distinct"><code class="xref py py-meth docutils literal notranslate"><span class="pre">distinct()</span></code></a> for an explanation of how
related model ordering can change the expected results.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>It is permissible to specify a multi-valued field to order the results by
(for example, a <a class="reference internal" href="fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> field, or the
reverse relation of a <a class="reference internal" href="fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> field).</p>
<p>Consider this case:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Event</span><span class="p">(</span><span class="n">Model</span><span class="p">):</span>
   <span class="n">parent</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
       <span class="s1">&#39;self&#39;</span><span class="p">,</span>
       <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
       <span class="n">related_name</span><span class="o">=</span><span class="s1">&#39;children&#39;</span><span class="p">,</span>
   <span class="p">)</span>
   <span class="n">date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>

<span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;children__date&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Here, there could potentially be multiple ordering data for each <code class="docutils literal notranslate"><span class="pre">Event</span></code>;
each <code class="docutils literal notranslate"><span class="pre">Event</span></code> with multiple <code class="docutils literal notranslate"><span class="pre">children</span></code> will be returned multiple times
into the new <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> that <code class="docutils literal notranslate"><span class="pre">order_by()</span></code> creates. In other words,
using <code class="docutils literal notranslate"><span class="pre">order_by()</span></code> on the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> could return more items than you
were working on to begin with - which is probably neither expected nor
useful.</p>
<p class="last">Thus, take care when using multi-valued field to order the results. <strong>If</strong>
you can be sure that there will only be one ordering piece of data for each
of the items you’re ordering, this approach should not present problems. If
not, make sure the results are what you expect.</p>
</div>
<p>There’s no way to specify whether ordering should be case sensitive. With
respect to case-sensitivity, Django will order results however your database
backend normally orders them.</p>
<p>You can order by a field converted to lowercase with
<a class="reference internal" href="database-functions.html#django.db.models.functions.Lower" title="django.db.models.functions.Lower"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lower</span></code></a> which will achieve case-consistent
ordering:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="n">Lower</span><span class="p">(</span><span class="s1">&#39;headline&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">desc</span><span class="p">())</span>
</pre></div>
</div>
<p>If you don’t want any ordering to be applied to a query, not even the default
ordering, call <a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><code class="xref py py-meth docutils literal notranslate"><span class="pre">order_by()</span></code></a> with no parameters.</p>
<p>You can tell if a query is ordered or not by checking the
<a class="reference internal" href="#django.db.models.query.QuerySet.ordered" title="django.db.models.query.QuerySet.ordered"><code class="xref py py-attr docutils literal notranslate"><span class="pre">QuerySet.ordered</span></code></a> attribute, which will be <code class="docutils literal notranslate"><span class="pre">True</span></code> if the
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> has been ordered in any way.</p>
<p>Each <code class="docutils literal notranslate"><span class="pre">order_by()</span></code> call will clear any previous ordering. For example, this
query will be ordered by <code class="docutils literal notranslate"><span class="pre">pub_date</span></code> and not <code class="docutils literal notranslate"><span class="pre">headline</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;headline&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;pub_date&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>Ordering is not a free operation. Each field you add to the ordering
incurs a cost to your database. Each foreign key you add will
implicitly include all of its default orderings as well.</p>
<p class="last">If a query doesn’t have an ordering specified, results are returned from
the database in an unspecified order. A particular ordering is guaranteed
only when ordering by a set of fields that uniquely identify each object in
the results. For example, if a <code class="docutils literal notranslate"><span class="pre">name</span></code> field isn’t unique, ordering by it
won’t guarantee objects with the same name always appear in the same order.</p>
</div>
</div>
<div class="section" id="s-reverse">
<span id="reverse"></span><h4><code class="docutils literal notranslate"><span class="pre">reverse()</span></code><a class="headerlink" href="#reverse" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.reverse">
<code class="descname">reverse</code>()<a class="headerlink" href="#django.db.models.query.QuerySet.reverse" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Use the <code class="docutils literal notranslate"><span class="pre">reverse()</span></code> method to reverse the order in which a queryset’s
elements are returned. Calling <code class="docutils literal notranslate"><span class="pre">reverse()</span></code> a second time restores the
ordering back to the normal direction.</p>
<p>To retrieve the “last” five items in a queryset, you could do this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">my_queryset</span><span class="o">.</span><span class="n">reverse</span><span class="p">()[:</span><span class="mi">5</span><span class="p">]</span>
</pre></div>
</div>
<p>Note that this is not quite the same as slicing from the end of a sequence in
Python. The above example will return the last item first, then the
penultimate item and so on. If we had a Python sequence and looked at
<code class="docutils literal notranslate"><span class="pre">seq[-5:]</span></code>, we would see the fifth-last item first. Django doesn’t support
that mode of access (slicing from the end), because it’s not possible to do it
efficiently in SQL.</p>
<p>Also, note that <code class="docutils literal notranslate"><span class="pre">reverse()</span></code> should generally only be called on a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>
which has a defined ordering (e.g., when querying against a model which defines
a default ordering, or when using <a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><code class="xref py py-meth docutils literal notranslate"><span class="pre">order_by()</span></code></a>). If no such ordering is
defined for a given <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>, calling <code class="docutils literal notranslate"><span class="pre">reverse()</span></code> on it has no real
effect (the ordering was undefined prior to calling <code class="docutils literal notranslate"><span class="pre">reverse()</span></code>, and will
remain undefined afterward).</p>
</div>
<div class="section" id="s-distinct">
<span id="distinct"></span><h4><code class="docutils literal notranslate"><span class="pre">distinct()</span></code><a class="headerlink" href="#distinct" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.distinct">
<code class="descname">distinct</code>(<em>*fields</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.distinct" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a new <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> that uses <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">DISTINCT</span></code> in its SQL query. This
eliminates duplicate rows from the query results.</p>
<p>By default, a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> will not eliminate duplicate rows. In practice, this
is rarely a problem, because simple queries such as <code class="docutils literal notranslate"><span class="pre">Blog.objects.all()</span></code>
don’t introduce the possibility of duplicate result rows. However, if your
query spans multiple tables, it’s possible to get duplicate results when a
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> is evaluated. That’s when you’d use <code class="docutils literal notranslate"><span class="pre">distinct()</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Any fields used in an <a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><code class="xref py py-meth docutils literal notranslate"><span class="pre">order_by()</span></code></a> call are included in the SQL
<code class="docutils literal notranslate"><span class="pre">SELECT</span></code> columns. This can sometimes lead to unexpected results when used
in conjunction with <code class="docutils literal notranslate"><span class="pre">distinct()</span></code>. If you order by fields from a related
model, those fields will be added to the selected columns and they may make
otherwise duplicate rows appear to be distinct. Since the extra columns
don’t appear in the returned results (they are only there to support
ordering), it sometimes looks like non-distinct results are being returned.</p>
<p>Similarly, if you use a <a class="reference internal" href="#django.db.models.query.QuerySet.values" title="django.db.models.query.QuerySet.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code></a> query to restrict the columns
selected, the columns used in any <a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><code class="xref py py-meth docutils literal notranslate"><span class="pre">order_by()</span></code></a> (or default model
ordering) will still be involved and may affect uniqueness of the results.</p>
<p class="last">The moral here is that if you are using <code class="docutils literal notranslate"><span class="pre">distinct()</span></code> be careful about
ordering by related models. Similarly, when using <code class="docutils literal notranslate"><span class="pre">distinct()</span></code> and
<a class="reference internal" href="#django.db.models.query.QuerySet.values" title="django.db.models.query.QuerySet.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code></a> together, be careful when ordering by fields not in the
<a class="reference internal" href="#django.db.models.query.QuerySet.values" title="django.db.models.query.QuerySet.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code></a> call.</p>
</div>
<p>On PostgreSQL only, you can pass positional arguments (<code class="docutils literal notranslate"><span class="pre">*fields</span></code>) in order to
specify the names of fields to which the <code class="docutils literal notranslate"><span class="pre">DISTINCT</span></code> should apply. This
translates to a <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">DISTINCT</span> <span class="pre">ON</span></code> SQL query. Here’s the difference. For a
normal <code class="docutils literal notranslate"><span class="pre">distinct()</span></code> call, the database compares <em>each</em> field in each row when
determining which rows are distinct. For a <code class="docutils literal notranslate"><span class="pre">distinct()</span></code> call with specified
field names, the database will only compare the specified field names.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>When you specify field names, you <em>must</em> provide an <code class="docutils literal notranslate"><span class="pre">order_by()</span></code> in the
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>, and the fields in <code class="docutils literal notranslate"><span class="pre">order_by()</span></code> must start with the fields in
<code class="docutils literal notranslate"><span class="pre">distinct()</span></code>, in the same order.</p>
<p class="last">For example, <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">DISTINCT</span> <span class="pre">ON</span> <span class="pre">(a)</span></code> gives you the first row for each
value in column <code class="docutils literal notranslate"><span class="pre">a</span></code>. If you don’t specify an order, you’ll get some
arbitrary row.</p>
</div>
<p>Examples (those after the first will only work on PostgreSQL):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">distinct</span><span class="p">()</span>
<span class="go">[...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;pub_date&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s1">&#39;pub_date&#39;</span><span class="p">)</span>
<span class="go">[...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;blog&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s1">&#39;blog&#39;</span><span class="p">)</span>
<span class="go">[...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;author&#39;</span><span class="p">,</span> <span class="s1">&#39;pub_date&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s1">&#39;author&#39;</span><span class="p">,</span> <span class="s1">&#39;pub_date&#39;</span><span class="p">)</span>
<span class="go">[...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;blog__name&#39;</span><span class="p">,</span> <span class="s1">&#39;mod_date&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s1">&#39;blog__name&#39;</span><span class="p">,</span> <span class="s1">&#39;mod_date&#39;</span><span class="p">)</span>
<span class="go">[...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;author&#39;</span><span class="p">,</span> <span class="s1">&#39;pub_date&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s1">&#39;author&#39;</span><span class="p">)</span>
<span class="go">[...]</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Keep in mind that <a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><code class="xref py py-meth docutils literal notranslate"><span class="pre">order_by()</span></code></a> uses any default related model ordering
that has been defined. You might have to explicitly order by the relation
<code class="docutils literal notranslate"><span class="pre">_id</span></code> or referenced field to make sure the <code class="docutils literal notranslate"><span class="pre">DISTINCT</span> <span class="pre">ON</span></code> expressions
match those at the beginning of the <code class="docutils literal notranslate"><span class="pre">ORDER</span> <span class="pre">BY</span></code> clause. For example, if
the <code class="docutils literal notranslate"><span class="pre">Blog</span></code> model defined an <a class="reference internal" href="options.html#django.db.models.Options.ordering" title="django.db.models.Options.ordering"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ordering</span></code></a> by
<code class="docutils literal notranslate"><span class="pre">name</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;blog&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s1">&#39;blog&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p class="last">…wouldn’t work because the query would be ordered by <code class="docutils literal notranslate"><span class="pre">blog__name</span></code> thus
mismatching the <code class="docutils literal notranslate"><span class="pre">DISTINCT</span> <span class="pre">ON</span></code> expression. You’d have to explicitly order
by the relation <cite>_id</cite> field (<code class="docutils literal notranslate"><span class="pre">blog_id</span></code> in this case) or the referenced
one (<code class="docutils literal notranslate"><span class="pre">blog__pk</span></code>) to make sure both expressions match.</p>
</div>
</div>
<div class="section" id="s-values">
<span id="values"></span><h4><code class="docutils literal notranslate"><span class="pre">values()</span></code><a class="headerlink" href="#values" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.values">
<code class="descname">values</code>(<em>*fields</em>, <em>**expressions</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.values" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> that returns dictionaries, rather than model instances,
when used as an iterable.</p>
<p>Each of those dictionaries represents an object, with the keys corresponding to
the attribute names of model objects.</p>
<p>This example compares the dictionaries of <code class="docutils literal notranslate"><span class="pre">values()</span></code> with the normal model
objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># This list contains a Blog object.</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name__startswith</span><span class="o">=</span><span class="s1">&#39;Beatles&#39;</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">QuerySet</span> <span class="p">[</span><span class="o">&lt;</span><span class="n">Blog</span><span class="p">:</span> <span class="n">Beatles</span> <span class="n">Blog</span><span class="o">&gt;</span><span class="p">]</span><span class="o">&gt;</span>

<span class="c1"># This list contains a dictionary.</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name__startswith</span><span class="o">=</span><span class="s1">&#39;Beatles&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>
<span class="o">&lt;</span><span class="n">QuerySet</span> <span class="p">[{</span><span class="s1">&#39;id&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;Beatles Blog&#39;</span><span class="p">,</span> <span class="s1">&#39;tagline&#39;</span><span class="p">:</span> <span class="s1">&#39;All the latest Beatles news.&#39;</span><span class="p">}]</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">values()</span></code> method takes optional positional arguments, <code class="docutils literal notranslate"><span class="pre">*fields</span></code>, which
specify field names to which the <code class="docutils literal notranslate"><span class="pre">SELECT</span></code> should be limited. If you specify
the fields, each dictionary will contain only the field keys/values for the
fields you specify. If you don’t specify the fields, each dictionary will
contain a key and value for every field in the database table.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>
<span class="go">&lt;QuerySet [{&#39;id&#39;: 1, &#39;name&#39;: &#39;Beatles Blog&#39;, &#39;tagline&#39;: &#39;All the latest Beatles news.&#39;}]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">,</span> <span class="s1">&#39;name&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [{&#39;id&#39;: 1, &#39;name&#39;: &#39;Beatles Blog&#39;}]&gt;</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">values()</span></code> method also takes optional keyword arguments,
<code class="docutils literal notranslate"><span class="pre">**expressions</span></code>, which are passed through to <a class="reference internal" href="#django.db.models.query.QuerySet.annotate" title="django.db.models.query.QuerySet.annotate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">annotate()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models.functions</span> <span class="k">import</span> <span class="n">Lower</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="n">lower_name</span><span class="o">=</span><span class="n">Lower</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">))</span>
<span class="go">&lt;QuerySet [{&#39;lower_name&#39;: &#39;beatles blog&#39;}]&gt;</span>
</pre></div>
</div>
<p>An aggregate within a <code class="docutils literal notranslate"><span class="pre">values()</span></code> clause is applied before other arguments
within the same <code class="docutils literal notranslate"><span class="pre">values()</span></code> clause. If you need to group by another value,
add it to an earlier <code class="docutils literal notranslate"><span class="pre">values()</span></code> clause instead. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="k">import</span> <span class="n">Count</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;entry__authors&#39;</span><span class="p">,</span> <span class="n">entries</span><span class="o">=</span><span class="n">Count</span><span class="p">(</span><span class="s1">&#39;entry&#39;</span><span class="p">))</span>
<span class="go">&lt;QuerySet [{&#39;entry__authors&#39;: 1, &#39;entries&#39;: 20}, {&#39;entry__authors&#39;: 1, &#39;entries&#39;: 13}]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;entry__authors&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span><span class="n">entries</span><span class="o">=</span><span class="n">Count</span><span class="p">(</span><span class="s1">&#39;entry&#39;</span><span class="p">))</span>
<span class="go">&lt;QuerySet [{&#39;entry__authors&#39;: 1, &#39;entries&#39;: 33}]&gt;</span>
</pre></div>
</div>
<p>A few subtleties that are worth mentioning:</p>
<ul>
<li><p class="first">If you have a field called <code class="docutils literal notranslate"><span class="pre">foo</span></code> that is a
<a class="reference internal" href="fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>, the default <code class="docutils literal notranslate"><span class="pre">values()</span></code> call
will return a dictionary key called <code class="docutils literal notranslate"><span class="pre">foo_id</span></code>, since this is the name
of the hidden model attribute that stores the actual value (the <code class="docutils literal notranslate"><span class="pre">foo</span></code>
attribute refers to the related model). When you are calling
<code class="docutils literal notranslate"><span class="pre">values()</span></code> and passing in field names, you can pass in either <code class="docutils literal notranslate"><span class="pre">foo</span></code>
or <code class="docutils literal notranslate"><span class="pre">foo_id</span></code> and you will get back the same thing (the dictionary key
will match the field name you passed in).</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>
<span class="go">&lt;QuerySet [{&#39;blog_id&#39;: 1, &#39;headline&#39;: &#39;First Entry&#39;, ...}, ...]&gt;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;blog&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [{&#39;blog&#39;: 1}, ...]&gt;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;blog_id&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [{&#39;blog_id&#39;: 1}, ...]&gt;</span>
</pre></div>
</div>
</li>
<li><p class="first">When using <code class="docutils literal notranslate"><span class="pre">values()</span></code> together with <a class="reference internal" href="#django.db.models.query.QuerySet.distinct" title="django.db.models.query.QuerySet.distinct"><code class="xref py py-meth docutils literal notranslate"><span class="pre">distinct()</span></code></a>, be aware that
ordering can affect the results. See the note in <a class="reference internal" href="#django.db.models.query.QuerySet.distinct" title="django.db.models.query.QuerySet.distinct"><code class="xref py py-meth docutils literal notranslate"><span class="pre">distinct()</span></code></a> for
details.</p>
</li>
<li><p class="first">If you use a <code class="docutils literal notranslate"><span class="pre">values()</span></code> clause after an <a class="reference internal" href="#django.db.models.query.QuerySet.extra" title="django.db.models.query.QuerySet.extra"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extra()</span></code></a> call,
any fields defined by a <code class="docutils literal notranslate"><span class="pre">select</span></code> argument in the <a class="reference internal" href="#django.db.models.query.QuerySet.extra" title="django.db.models.query.QuerySet.extra"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extra()</span></code></a> must
be explicitly included in the <code class="docutils literal notranslate"><span class="pre">values()</span></code> call. Any <a class="reference internal" href="#django.db.models.query.QuerySet.extra" title="django.db.models.query.QuerySet.extra"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extra()</span></code></a> call
made after a <code class="docutils literal notranslate"><span class="pre">values()</span></code> call will have its extra selected fields
ignored.</p>
</li>
<li><p class="first">Calling <a class="reference internal" href="#django.db.models.query.QuerySet.only" title="django.db.models.query.QuerySet.only"><code class="xref py py-meth docutils literal notranslate"><span class="pre">only()</span></code></a> and <a class="reference internal" href="#django.db.models.query.QuerySet.defer" title="django.db.models.query.QuerySet.defer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">defer()</span></code></a> after <code class="docutils literal notranslate"><span class="pre">values()</span></code> doesn’t make
sense, so doing so will raise a <code class="docutils literal notranslate"><span class="pre">NotImplementedError</span></code>.</p>
</li>
</ul>
<p>It is useful when you know you’re only going to need values from a small number
of the available fields and you won’t need the functionality of a model
instance object. It’s more efficient to select only the fields you need to use.</p>
<p>Finally, note that you can call <code class="docutils literal notranslate"><span class="pre">filter()</span></code>, <code class="docutils literal notranslate"><span class="pre">order_by()</span></code>, etc. after the
<code class="docutils literal notranslate"><span class="pre">values()</span></code> call, that means that these two calls are identical:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">()</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">)</span>
<span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>
</pre></div>
</div>
<p>The people who made Django prefer to put all the SQL-affecting methods first,
followed (optionally) by any output-affecting methods (such as <code class="docutils literal notranslate"><span class="pre">values()</span></code>),
but it doesn’t really matter. This is your chance to really flaunt your
individualism.</p>
<p>You can also refer to fields on related models with reverse relations through
<code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code>, <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> and <code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code> attributes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;entry__headline&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [{&#39;name&#39;: &#39;My blog&#39;, &#39;entry__headline&#39;: &#39;An entry&#39;},</span>
<span class="go">     {&#39;name&#39;: &#39;My blog&#39;, &#39;entry__headline&#39;: &#39;Another entry&#39;}, ...]&gt;</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Because <a class="reference internal" href="fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> attributes and reverse
relations can have multiple related rows, including these can have a
multiplier effect on the size of your result set. This will be especially
pronounced if you include multiple such fields in your <code class="docutils literal notranslate"><span class="pre">values()</span></code> query,
in which case all possible combinations will be returned.</p>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 1.11:</span> <p>Support for <code class="docutils literal notranslate"><span class="pre">**expressions</span></code> was added.</p>
</div>
</div>
<div class="section" id="s-values-list">
<span id="values-list"></span><h4><code class="docutils literal notranslate"><span class="pre">values_list()</span></code><a class="headerlink" href="#values-list" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.values_list">
<code class="descname">values_list</code>(<em>*fields</em>, <em>flat=False</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.values_list" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>This is similar to <code class="docutils literal notranslate"><span class="pre">values()</span></code> except that instead of returning dictionaries,
it returns tuples when iterated over. Each tuple contains the value from the
respective field or expression passed into the <code class="docutils literal notranslate"><span class="pre">values_list()</span></code> call — so the
first item is the first field, etc. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">,</span> <span class="s1">&#39;headline&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [(1, &#39;First entry&#39;), ...]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models.functions</span> <span class="k">import</span> <span class="n">Lower</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">,</span> <span class="n">Lower</span><span class="p">(</span><span class="s1">&#39;headline&#39;</span><span class="p">))</span>
<span class="go">&lt;QuerySet [(1, &#39;first entry&#39;), ...]&gt;</span>
</pre></div>
</div>
<p>If you only pass in a single field, you can also pass in the <code class="docutils literal notranslate"><span class="pre">flat</span></code>
parameter. If <code class="docutils literal notranslate"><span class="pre">True</span></code>, this will mean the returned results are single values,
rather than one-tuples. An example should make the difference clearer:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet[(1,), (2,), (3,), ...]&gt;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">,</span> <span class="n">flat</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [1, 2, 3, ...]&gt;</span>
</pre></div>
</div>
<p>It is an error to pass in <code class="docutils literal notranslate"><span class="pre">flat</span></code> when there is more than one field.</p>
<p>If you don’t pass any values to <code class="docutils literal notranslate"><span class="pre">values_list()</span></code>, it will return all the
fields in the model, in the order they were declared.</p>
<p>A common need is to get a specific field value of a certain model instance. To
achieve that, use <code class="docutils literal notranslate"><span class="pre">values_list()</span></code> followed by a <code class="docutils literal notranslate"><span class="pre">get()</span></code> call:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;headline&#39;</span><span class="p">,</span> <span class="n">flat</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;First entry&#39;</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">values()</span></code> and <code class="docutils literal notranslate"><span class="pre">values_list()</span></code> are both intended as optimizations for a
specific use case: retrieving a subset of data without the overhead of creating
a model instance. This metaphor falls apart when dealing with many-to-many and
other multivalued relations (such as the one-to-many relation of a reverse
foreign key) because the “one row, one object” assumption doesn’t hold.</p>
<p>For example, notice the behavior when querying across a
<a class="reference internal" href="fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;entry__headline&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [(&#39;Noam Chomsky&#39;, &#39;Impressions of Gaza&#39;),</span>
<span class="go"> (&#39;George Orwell&#39;, &#39;Why Socialists Do Not Believe in Fun&#39;),</span>
<span class="go"> (&#39;George Orwell&#39;, &#39;In Defence of English Cooking&#39;),</span>
<span class="go"> (&#39;Don Quixote&#39;, None)]&gt;</span>
</pre></div>
</div>
<p>Authors with multiple entries appear multiple times and authors without any
entries have <code class="docutils literal notranslate"><span class="pre">None</span></code> for the entry headline.</p>
<p>Similarly, when querying a reverse foreign key, <code class="docutils literal notranslate"><span class="pre">None</span></code> appears for entries
not having any author:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;authors&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [(&#39;Noam Chomsky&#39;,), (&#39;George Orwell&#39;,), (None,)]&gt;</span>
</pre></div>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 1.11:</span> <p>Support for expressions in <code class="docutils literal notranslate"><span class="pre">*fields</span></code> was added.</p>
</div>
</div>
<div class="section" id="s-dates">
<span id="dates"></span><h4><code class="docutils literal notranslate"><span class="pre">dates()</span></code><a class="headerlink" href="#dates" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.dates">
<code class="descname">dates</code>(<em>field</em>, <em>kind</em>, <em>order='ASC'</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.dates" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> that evaluates to a list of <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.date" title="(in Python v3.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a>
objects representing all available dates of a particular kind within the
contents of the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">field</span></code> should be the name of a <code class="docutils literal notranslate"><span class="pre">DateField</span></code> of your model.
<code class="docutils literal notranslate"><span class="pre">kind</span></code> should be either <code class="docutils literal notranslate"><span class="pre">&quot;year&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;month&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;day&quot;</span></code>. Each
<code class="docutils literal notranslate"><span class="pre">datetime.date</span></code> object in the result list is “truncated” to the given
<code class="docutils literal notranslate"><span class="pre">type</span></code>.</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">&quot;year&quot;</span></code> returns a list of all distinct year values for the field.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;month&quot;</span></code> returns a list of all distinct year/month values for the
field.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;day&quot;</span></code> returns a list of all distinct year/month/day values for the
field.</li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">order</span></code>, which defaults to <code class="docutils literal notranslate"><span class="pre">'ASC'</span></code>, should be either <code class="docutils literal notranslate"><span class="pre">'ASC'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'DESC'</span></code>. This specifies how to order the results.</p>
<p>Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">dates</span><span class="p">(</span><span class="s1">&#39;pub_date&#39;</span><span class="p">,</span> <span class="s1">&#39;year&#39;</span><span class="p">)</span>
<span class="go">[datetime.date(2005, 1, 1)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">dates</span><span class="p">(</span><span class="s1">&#39;pub_date&#39;</span><span class="p">,</span> <span class="s1">&#39;month&#39;</span><span class="p">)</span>
<span class="go">[datetime.date(2005, 2, 1), datetime.date(2005, 3, 1)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">dates</span><span class="p">(</span><span class="s1">&#39;pub_date&#39;</span><span class="p">,</span> <span class="s1">&#39;day&#39;</span><span class="p">)</span>
<span class="go">[datetime.date(2005, 2, 20), datetime.date(2005, 3, 20)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">dates</span><span class="p">(</span><span class="s1">&#39;pub_date&#39;</span><span class="p">,</span> <span class="s1">&#39;day&#39;</span><span class="p">,</span> <span class="n">order</span><span class="o">=</span><span class="s1">&#39;DESC&#39;</span><span class="p">)</span>
<span class="go">[datetime.date(2005, 3, 20), datetime.date(2005, 2, 20)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">dates</span><span class="p">(</span><span class="s1">&#39;pub_date&#39;</span><span class="p">,</span> <span class="s1">&#39;day&#39;</span><span class="p">)</span>
<span class="go">[datetime.date(2005, 3, 20)]</span>
</pre></div>
</div>
</div>
<div class="section" id="s-datetimes">
<span id="datetimes"></span><h4><code class="docutils literal notranslate"><span class="pre">datetimes()</span></code><a class="headerlink" href="#datetimes" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.datetimes">
<code class="descname">datetimes</code>(<em>field_name</em>, <em>kind</em>, <em>order='ASC'</em>, <em>tzinfo=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.datetimes" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> that evaluates to a list of <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.datetime" title="(in Python v3.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.datetime</span></code></a>
objects representing all available dates of a particular kind within the
contents of the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">field_name</span></code> should be the name of a <code class="docutils literal notranslate"><span class="pre">DateTimeField</span></code> of your model.</p>
<p><code class="docutils literal notranslate"><span class="pre">kind</span></code> should be either <code class="docutils literal notranslate"><span class="pre">&quot;year&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;month&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;day&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;hour&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;minute&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;second&quot;</span></code>. Each <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> object in the result
list is “truncated” to the given <code class="docutils literal notranslate"><span class="pre">type</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">order</span></code>, which defaults to <code class="docutils literal notranslate"><span class="pre">'ASC'</span></code>, should be either <code class="docutils literal notranslate"><span class="pre">'ASC'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'DESC'</span></code>. This specifies how to order the results.</p>
<p><code class="docutils literal notranslate"><span class="pre">tzinfo</span></code> defines the time zone to which datetimes are converted prior to
truncation. Indeed, a given datetime has different representations depending
on the time zone in use. This parameter must be a <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.tzinfo" title="(in Python v3.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.tzinfo</span></code></a>
object. If it’s <code class="docutils literal notranslate"><span class="pre">None</span></code>, Django uses the <a class="reference internal" href="../../topics/i18n/timezones.html#default-current-time-zone"><span class="std std-ref">current time zone</span></a>. It has no effect when <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is
<code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<div class="admonition note" id="database-time-zone-definitions">
<p class="first admonition-title">Note</p>
<p>This function performs time zone conversions directly in the database.
As a consequence, your database must be able to interpret the value of
<code class="docutils literal notranslate"><span class="pre">tzinfo.tzname(None)</span></code>. This translates into the following requirements:</p>
<ul class="last simple">
<li>SQLite: no requirements. Conversions are performed in Python with <a class="reference external" href="http://pytz.sourceforge.net/">pytz</a>
(installed when you install Django).</li>
<li>PostgreSQL: no requirements (see <a class="reference external" href="https://www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-TIMEZONES">Time Zones</a>).</li>
<li>Oracle: no requirements (see <a class="reference external" href="https://docs.oracle.com/database/121/NLSPG/ch4datetime.htm#NLSPG258">Choosing a Time Zone File</a>).</li>
<li>MySQL: load the time zone tables with <a class="reference external" href="https://dev.mysql.com/doc/refman/en/mysql-tzinfo-to-sql.html">mysql_tzinfo_to_sql</a>.</li>
</ul>
</div>
</div>
<div class="section" id="s-none">
<span id="none"></span><h4><code class="docutils literal notranslate"><span class="pre">none()</span></code><a class="headerlink" href="#none" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.none">
<code class="descname">none</code>()<a class="headerlink" href="#django.db.models.query.QuerySet.none" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Calling none() will create a queryset that never returns any objects and no
query will be executed when accessing the results. A qs.none() queryset
is an instance of <code class="docutils literal notranslate"><span class="pre">EmptyQuerySet</span></code>.</p>
<p>Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">none</span><span class="p">()</span>
<span class="go">&lt;QuerySet []&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models.query</span> <span class="k">import</span> <span class="n">EmptyQuerySet</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">none</span><span class="p">(),</span> <span class="n">EmptyQuerySet</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
<div class="section" id="s-all">
<span id="all"></span><h4><code class="docutils literal notranslate"><span class="pre">all()</span></code><a class="headerlink" href="#all" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.all">
<code class="descname">all</code>()<a class="headerlink" href="#django.db.models.query.QuerySet.all" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <em>copy</em> of the current <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> (or <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> subclass).  This
can be useful in situations where you might want to pass in either a model
manager or a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> and do further filtering on the result. After calling
<code class="docutils literal notranslate"><span class="pre">all()</span></code> on either object, you’ll definitely have a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> to work with.</p>
<p>When a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> is <a class="reference internal" href="#when-querysets-are-evaluated"><span class="std std-ref">evaluated</span></a>, it
typically caches its results. If the data in the database might have changed
since a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> was evaluated, you can get updated results for the same
query by calling <code class="docutils literal notranslate"><span class="pre">all()</span></code> on a previously evaluated <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>.</p>
</div>
<div class="section" id="s-union">
<span id="union"></span><h4><code class="docutils literal notranslate"><span class="pre">union()</span></code><a class="headerlink" href="#union" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.union">
<code class="descname">union</code>(<em>*other_qs</em>, <em>all=False</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.union" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.11.</span> </div>
<p>Uses SQL’s <code class="docutils literal notranslate"><span class="pre">UNION</span></code> operator to combine the results of two or more
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">qs1</span><span class="o">.</span><span class="n">union</span><span class="p">(</span><span class="n">qs2</span><span class="p">,</span> <span class="n">qs3</span><span class="p">)</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">UNION</span></code> operator selects only distinct values by default. To allow
duplicate values, use the <code class="docutils literal notranslate"><span class="pre">all=True</span></code> argument.</p>
<p><code class="docutils literal notranslate"><span class="pre">union()</span></code>, <code class="docutils literal notranslate"><span class="pre">intersection()</span></code>, and <code class="docutils literal notranslate"><span class="pre">difference()</span></code> return model instances
of the type of the first <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> even if the arguments are <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s
of other models. Passing different models works as long as the <code class="docutils literal notranslate"><span class="pre">SELECT</span></code> list
is the same in all <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s (at least the types, the names don’t matter
as long as the types in the same order). In such cases, you must use the column
names from the first <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> in <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> methods applied to the
resulting <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">qs1</span> <span class="o">=</span> <span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">qs2</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;headline&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">qs1</span><span class="o">.</span><span class="n">union</span><span class="p">(</span><span class="n">qs2</span><span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>In addition, only <code class="docutils literal notranslate"><span class="pre">LIMIT</span></code>, <code class="docutils literal notranslate"><span class="pre">OFFSET</span></code>, <code class="docutils literal notranslate"><span class="pre">COUNT(*)</span></code>, <code class="docutils literal notranslate"><span class="pre">ORDER</span> <span class="pre">BY</span></code>, and
specifying columns (i.e. slicing, <a class="reference internal" href="#django.db.models.query.QuerySet.count" title="django.db.models.query.QuerySet.count"><code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code></a>, <a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><code class="xref py py-meth docutils literal notranslate"><span class="pre">order_by()</span></code></a>, and
<a class="reference internal" href="#django.db.models.query.QuerySet.values" title="django.db.models.query.QuerySet.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code></a>/<a class="reference internal" href="#django.db.models.query.QuerySet.values_list" title="django.db.models.query.QuerySet.values_list"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values_list()</span></code></a>) are allowed on the resulting
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>. Further, databases place restrictions on what operations are
allowed in the combined queries. For example, most databases don’t allow
<code class="docutils literal notranslate"><span class="pre">LIMIT</span></code> or <code class="docutils literal notranslate"><span class="pre">OFFSET</span></code> in the combined queries.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.11.4:</span> <p><code class="docutils literal notranslate"><span class="pre">COUNT(*)</span></code> support was added.</p>
</div>
</div>
<div class="section" id="s-intersection">
<span id="intersection"></span><h4><code class="docutils literal notranslate"><span class="pre">intersection()</span></code><a class="headerlink" href="#intersection" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.intersection">
<code class="descname">intersection</code>(<em>*other_qs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.intersection" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.11.</span> </div>
<p>Uses SQL’s <code class="docutils literal notranslate"><span class="pre">INTERSECT</span></code> operator to return the shared elements of two or more
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">qs1</span><span class="o">.</span><span class="n">intersection</span><span class="p">(</span><span class="n">qs2</span><span class="p">,</span> <span class="n">qs3</span><span class="p">)</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="#django.db.models.query.QuerySet.union" title="django.db.models.query.QuerySet.union"><code class="xref py py-meth docutils literal notranslate"><span class="pre">union()</span></code></a> for some restrictions.</p>
</div>
<div class="section" id="s-difference">
<span id="difference"></span><h4><code class="docutils literal notranslate"><span class="pre">difference()</span></code><a class="headerlink" href="#difference" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.difference">
<code class="descname">difference</code>(<em>*other_qs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.difference" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.11.</span> </div>
<p>Uses SQL’s <code class="docutils literal notranslate"><span class="pre">EXCEPT</span></code> operator to keep only elements present in the
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> but not in some other <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">qs1</span><span class="o">.</span><span class="n">difference</span><span class="p">(</span><span class="n">qs2</span><span class="p">,</span> <span class="n">qs3</span><span class="p">)</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="#django.db.models.query.QuerySet.union" title="django.db.models.query.QuerySet.union"><code class="xref py py-meth docutils literal notranslate"><span class="pre">union()</span></code></a> for some restrictions.</p>
</div>
<div class="section" id="s-select-related">
<span id="select-related"></span><h4><code class="docutils literal notranslate"><span class="pre">select_related()</span></code><a class="headerlink" href="#select-related" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.select_related">
<code class="descname">select_related</code>(<em>*fields</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.select_related" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> that will “follow” foreign-key relationships, selecting
additional related-object data when it executes its query. This is a
performance booster which results in a single more complex query but means
later use of foreign-key relationships won’t require database queries.</p>
<p>The following examples illustrate the difference between plain lookups and
<code class="docutils literal notranslate"><span class="pre">select_related()</span></code> lookups. Here’s standard lookup:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Hits the database.</span>
<span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>

<span class="c1"># Hits the database again to get the related Blog object.</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">blog</span>
</pre></div>
</div>
<p>And here’s <code class="docutils literal notranslate"><span class="pre">select_related</span></code> lookup:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Hits the database.</span>
<span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s1">&#39;blog&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>

<span class="c1"># Doesn&#39;t hit the database, because e.blog has been prepopulated</span>
<span class="c1"># in the previous query.</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">blog</span>
</pre></div>
</div>
<p>You can use <code class="docutils literal notranslate"><span class="pre">select_related()</span></code> with any queryset of objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.utils</span> <span class="k">import</span> <span class="n">timezone</span>

<span class="c1"># Find all the blogs with entries scheduled to be published in the future.</span>
<span class="n">blogs</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>

<span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__gt</span><span class="o">=</span><span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">())</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s1">&#39;blog&#39;</span><span class="p">):</span>
    <span class="c1"># Without select_related(), this would make a database query for each</span>
    <span class="c1"># loop iteration in order to fetch the related blog for each entry.</span>
    <span class="n">blogs</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">blog</span><span class="p">)</span>
</pre></div>
</div>
<p>The order of <code class="docutils literal notranslate"><span class="pre">filter()</span></code> and <code class="docutils literal notranslate"><span class="pre">select_related()</span></code> chaining isn’t important.
These querysets are equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__gt</span><span class="o">=</span><span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">())</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s1">&#39;blog&#39;</span><span class="p">)</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s1">&#39;blog&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__gt</span><span class="o">=</span><span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
</pre></div>
</div>
<p>You can follow foreign keys in a similar way to querying them. If you have the
following models:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">City</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="n">hometown</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="n">City</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">SET_NULL</span><span class="p">,</span>
        <span class="n">blank</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
        <span class="n">null</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
    <span class="p">)</span>

<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="n">author</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Person</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
</pre></div>
</div>
<p>… then a call to <code class="docutils literal notranslate"><span class="pre">Book.objects.select_related('author__hometown').get(id=4)</span></code>
will cache the related <code class="docutils literal notranslate"><span class="pre">Person</span></code> <em>and</em> the related <code class="docutils literal notranslate"><span class="pre">City</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">b</span> <span class="o">=</span> <span class="n">Book</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s1">&#39;author__hometown&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">b</span><span class="o">.</span><span class="n">author</span>         <span class="c1"># Doesn&#39;t hit the database.</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">hometown</span>       <span class="c1"># Doesn&#39;t hit the database.</span>

<span class="n">b</span> <span class="o">=</span> <span class="n">Book</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span> <span class="c1"># No select_related() in this example.</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">b</span><span class="o">.</span><span class="n">author</span>         <span class="c1"># Hits the database.</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">hometown</span>       <span class="c1"># Hits the database.</span>
</pre></div>
</div>
<p>You can refer to any <a class="reference internal" href="fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> or
<a class="reference internal" href="fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><code class="xref py py-class docutils literal notranslate"><span class="pre">OneToOneField</span></code></a> relation in the list of fields
passed to <code class="docutils literal notranslate"><span class="pre">select_related()</span></code>.</p>
<p>You can also refer to the reverse direction of a
<a class="reference internal" href="fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><code class="xref py py-class docutils literal notranslate"><span class="pre">OneToOneField</span></code></a> in the list of fields passed to
<code class="docutils literal notranslate"><span class="pre">select_related</span></code> — that is, you can traverse a
<a class="reference internal" href="fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><code class="xref py py-class docutils literal notranslate"><span class="pre">OneToOneField</span></code></a> back to the object on which the field
is defined. Instead of specifying the field name, use the <a class="reference internal" href="fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">related_name</span></code></a> for the field on the related object.</p>
<p>There may be some situations where you wish to call <code class="docutils literal notranslate"><span class="pre">select_related()</span></code> with a
lot of related objects, or where you don’t know all of the relations. In these
cases it is possible to call <code class="docutils literal notranslate"><span class="pre">select_related()</span></code> with no arguments. This will
follow all non-null foreign keys it can find - nullable foreign keys must be
specified. This is not recommended in most cases as it is likely to make the
underlying query more complex, and return more data, than is actually needed.</p>
<p>If you need to clear the list of related fields added by past calls of
<code class="docutils literal notranslate"><span class="pre">select_related</span></code> on a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>, you can pass <code class="docutils literal notranslate"><span class="pre">None</span></code> as a parameter:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">without_relations</span> <span class="o">=</span> <span class="n">queryset</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>Chaining <code class="docutils literal notranslate"><span class="pre">select_related</span></code> calls works in a similar way to other methods -
that is that <code class="docutils literal notranslate"><span class="pre">select_related('foo',</span> <span class="pre">'bar')</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">select_related('foo').select_related('bar')</span></code>.</p>
</div>
<div class="section" id="s-prefetch-related">
<span id="prefetch-related"></span><h4><code class="docutils literal notranslate"><span class="pre">prefetch_related()</span></code><a class="headerlink" href="#prefetch-related" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.prefetch_related">
<code class="descname">prefetch_related</code>(<em>*lookups</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.prefetch_related" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> that will automatically retrieve, in a single batch,
related objects for each of the specified lookups.</p>
<p>This has a similar purpose to <code class="docutils literal notranslate"><span class="pre">select_related</span></code>, in that both are designed to
stop the deluge of database queries that is caused by accessing related objects,
but the strategy is quite different.</p>
<p><code class="docutils literal notranslate"><span class="pre">select_related</span></code> works by creating an SQL join and including the fields of the
related object in the <code class="docutils literal notranslate"><span class="pre">SELECT</span></code> statement. For this reason, <code class="docutils literal notranslate"><span class="pre">select_related</span></code>
gets the related objects in the same database query. However, to avoid the much
larger result set that would result from joining across a ‘many’ relationship,
<code class="docutils literal notranslate"><span class="pre">select_related</span></code> is limited to single-valued relationships - foreign key and
one-to-one.</p>
<p><code class="docutils literal notranslate"><span class="pre">prefetch_related</span></code>, on the other hand, does a separate lookup for each
relationship, and does the ‘joining’ in Python. This allows it to prefetch
many-to-many and many-to-one objects, which cannot be done using
<code class="docutils literal notranslate"><span class="pre">select_related</span></code>, in addition to the foreign key and one-to-one relationships
that are supported by <code class="docutils literal notranslate"><span class="pre">select_related</span></code>. It also supports prefetching of
<a class="reference internal" href="../contrib/contenttypes.html#django.contrib.contenttypes.fields.GenericRelation" title="django.contrib.contenttypes.fields.GenericRelation"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericRelation</span></code></a> and
<a class="reference internal" href="../contrib/contenttypes.html#django.contrib.contenttypes.fields.GenericForeignKey" title="django.contrib.contenttypes.fields.GenericForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericForeignKey</span></code></a>, however, it
must be restricted to a homogeneous set of results. For example, prefetching
objects referenced by a <code class="docutils literal notranslate"><span class="pre">GenericForeignKey</span></code> is only supported if the query
is restricted to one <code class="docutils literal notranslate"><span class="pre">ContentType</span></code>.</p>
<p>For example, suppose you have these models:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Topping</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Pizza</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">toppings</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Topping</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>              <span class="c1"># __unicode__ on Python 2</span>
        <span class="k">return</span> <span class="s2">&quot;</span><span class="si">%s</span><span class="s2"> (</span><span class="si">%s</span><span class="s2">)&quot;</span> <span class="o">%</span> <span class="p">(</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
            <span class="s2">&quot;, &quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">topping</span><span class="o">.</span><span class="n">name</span> <span class="k">for</span> <span class="n">topping</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">toppings</span><span class="o">.</span><span class="n">all</span><span class="p">()),</span>
        <span class="p">)</span>
</pre></div>
</div>
<p>and run:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&quot;Hawaiian (ham, pineapple)&quot;, &quot;Seafood (prawns, smoked salmon)&quot;...</span>
</pre></div>
</div>
<p>The problem with this is that every time <code class="docutils literal notranslate"><span class="pre">Pizza.__str__()</span></code> asks for
<code class="docutils literal notranslate"><span class="pre">self.toppings.all()</span></code> it has to query the database, so
<code class="docutils literal notranslate"><span class="pre">Pizza.objects.all()</span></code> will run a query on the Toppings table for <strong>every</strong>
item in the Pizza <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>.</p>
<p>We can reduce to just two queries using <code class="docutils literal notranslate"><span class="pre">prefetch_related</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="s1">&#39;toppings&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This implies a <code class="docutils literal notranslate"><span class="pre">self.toppings.all()</span></code> for each <code class="docutils literal notranslate"><span class="pre">Pizza</span></code>; now each time
<code class="docutils literal notranslate"><span class="pre">self.toppings.all()</span></code> is called, instead of having to go to the database for
the items, it will find them in a prefetched <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> cache that was
populated in a single query.</p>
<p>That is, all the relevant toppings will have been fetched in a single query,
and used to make <code class="docutils literal notranslate"><span class="pre">QuerySets</span></code> that have a pre-filled cache of the relevant
results; these <code class="docutils literal notranslate"><span class="pre">QuerySets</span></code> are then used in the <code class="docutils literal notranslate"><span class="pre">self.toppings.all()</span></code> calls.</p>
<p>The additional queries in <code class="docutils literal notranslate"><span class="pre">prefetch_related()</span></code> are executed after the
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> has begun to be evaluated and the primary query has been executed.</p>
<p>If you have an iterable of model instances, you can prefetch related attributes
on those instances using the <a class="reference internal" href="#django.db.models.prefetch_related_objects" title="django.db.models.prefetch_related_objects"><code class="xref py py-func docutils literal notranslate"><span class="pre">prefetch_related_objects()</span></code></a>
function.</p>
<p>Note that the result cache of the primary <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> and all specified related
objects will then be fully loaded into memory. This changes the typical
behavior of <code class="docutils literal notranslate"><span class="pre">QuerySets</span></code>, which normally try to avoid loading all objects into
memory before they are needed, even after a query has been executed in the
database.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Remember that, as always with <code class="docutils literal notranslate"><span class="pre">QuerySets</span></code>, any subsequent chained methods
which imply a different database query will ignore previously cached
results, and retrieve data using a fresh database query. So, if you write
the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pizzas</span> <span class="o">=</span> <span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="s1">&#39;toppings&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="nb">list</span><span class="p">(</span><span class="n">pizza</span><span class="o">.</span><span class="n">toppings</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">spicy</span><span class="o">=</span><span class="kc">True</span><span class="p">))</span> <span class="k">for</span> <span class="n">pizza</span> <span class="ow">in</span> <span class="n">pizzas</span><span class="p">]</span>
</pre></div>
</div>
<p>…then the fact that <code class="docutils literal notranslate"><span class="pre">pizza.toppings.all()</span></code> has been prefetched will not
help you. The <code class="docutils literal notranslate"><span class="pre">prefetch_related('toppings')</span></code> implied
<code class="docutils literal notranslate"><span class="pre">pizza.toppings.all()</span></code>, but <code class="docutils literal notranslate"><span class="pre">pizza.toppings.filter()</span></code> is a new and
different query. The prefetched cache can’t help here; in fact it hurts
performance, since you have done a database query that you haven’t used. So
use this feature with caution!</p>
<p>Also, if you call the database-altering methods
<a class="reference internal" href="relations.html#django.db.models.fields.related.RelatedManager.add" title="django.db.models.fields.related.RelatedManager.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a>,
<a class="reference internal" href="relations.html#django.db.models.fields.related.RelatedManager.remove" title="django.db.models.fields.related.RelatedManager.remove"><code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code></a>,
<a class="reference internal" href="relations.html#django.db.models.fields.related.RelatedManager.clear" title="django.db.models.fields.related.RelatedManager.clear"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code></a> or
<a class="reference internal" href="relations.html#django.db.models.fields.related.RelatedManager.set" title="django.db.models.fields.related.RelatedManager.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a>, on
<a class="reference internal" href="relations.html#django.db.models.fields.related.RelatedManager" title="django.db.models.fields.related.RelatedManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">related</span> <span class="pre">managers</span></code></a>,
any prefetched cache for the relation will be cleared.</p>
<div class="last versionchanged">
<span class="title">Changed in Django 1.11:</span> <p>The clearing of the prefetched cache described above was added.</p>
</div>
</div>
<p>You can also use the normal join syntax to do related fields of related
fields. Suppose we have an additional model to the example above:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Restaurant</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">pizzas</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Pizza</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s1">&#39;restaurants&#39;</span><span class="p">)</span>
    <span class="n">best_pizza</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Pizza</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s1">&#39;championed_by&#39;</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
</pre></div>
</div>
<p>The following are all legal:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="s1">&#39;pizzas__toppings&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This will prefetch all pizzas belonging to restaurants, and all toppings
belonging to those pizzas. This will result in a total of 3 database queries -
one for the restaurants, one for the pizzas, and one for the toppings.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="s1">&#39;best_pizza__toppings&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This will fetch the best pizza and all the toppings for the best pizza for each
restaurant. This will be done in 3 database queries - one for the restaurants,
one for the ‘best pizzas’, and one for the toppings.</p>
<p>Of course, the <code class="docutils literal notranslate"><span class="pre">best_pizza</span></code> relationship could also be fetched using
<code class="docutils literal notranslate"><span class="pre">select_related</span></code> to reduce the query count to 2:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s1">&#39;best_pizza&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="s1">&#39;best_pizza__toppings&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Since the prefetch is executed after the main query (which includes the joins
needed by <code class="docutils literal notranslate"><span class="pre">select_related</span></code>), it is able to detect that the <code class="docutils literal notranslate"><span class="pre">best_pizza</span></code>
objects have already been fetched, and it will skip fetching them again.</p>
<p>Chaining <code class="docutils literal notranslate"><span class="pre">prefetch_related</span></code> calls will accumulate the lookups that are
prefetched. To clear any <code class="docutils literal notranslate"><span class="pre">prefetch_related</span></code> behavior, pass <code class="docutils literal notranslate"><span class="pre">None</span></code> as a
parameter:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">non_prefetched</span> <span class="o">=</span> <span class="n">qs</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>One difference to note when using <code class="docutils literal notranslate"><span class="pre">prefetch_related</span></code> is that objects created
by a query can be shared between the different objects that they are related to
i.e. a single Python model instance can appear at more than one point in the
tree of objects that are returned. This will normally happen with foreign key
relationships. Typically this behavior will not be a problem, and will in fact
save both memory and CPU time.</p>
<p>While <code class="docutils literal notranslate"><span class="pre">prefetch_related</span></code> supports prefetching <code class="docutils literal notranslate"><span class="pre">GenericForeignKey</span></code>
relationships, the number of queries will depend on the data. Since a
<code class="docutils literal notranslate"><span class="pre">GenericForeignKey</span></code> can reference data in multiple tables, one query per table
referenced is needed, rather than one query for all the items. There could be
additional queries on the <code class="docutils literal notranslate"><span class="pre">ContentType</span></code> table if the relevant rows have not
already been fetched.</p>
<p><code class="docutils literal notranslate"><span class="pre">prefetch_related</span></code> in most cases will be implemented using an SQL query that
uses the ‘IN’ operator. This means that for a large <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> a large ‘IN’ clause
could be generated, which, depending on the database, might have performance
problems of its own when it comes to parsing or executing the SQL query. Always
profile for your use case!</p>
<p>Note that if you use <code class="docutils literal notranslate"><span class="pre">iterator()</span></code> to run the query, <code class="docutils literal notranslate"><span class="pre">prefetch_related()</span></code>
calls will be ignored since these two optimizations do not make sense together.</p>
<p>You can use the <a class="reference internal" href="#django.db.models.Prefetch" title="django.db.models.Prefetch"><code class="xref py py-class docutils literal notranslate"><span class="pre">Prefetch</span></code></a> object to further control
the prefetch operation.</p>
<p>In its simplest form <code class="docutils literal notranslate"><span class="pre">Prefetch</span></code> is equivalent to the traditional string based
lookups:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="k">import</span> <span class="n">Prefetch</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;pizzas__toppings&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>You can provide a custom queryset with the optional <code class="docutils literal notranslate"><span class="pre">queryset</span></code> argument.
This can be used to change the default ordering of the queryset:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;pizzas__toppings&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">Toppings</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">)))</span>
</pre></div>
</div>
<p>Or to call <a class="reference internal" href="#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><code class="xref py py-meth docutils literal notranslate"><span class="pre">select_related()</span></code></a> when
applicable to reduce the number of queries even further:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;restaurants&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s1">&#39;best_pizza&#39;</span><span class="p">)))</span>
</pre></div>
</div>
<p>You can also assign the prefetched result to a custom attribute with the optional
<code class="docutils literal notranslate"><span class="pre">to_attr</span></code> argument. The result will be stored directly in a list.</p>
<p>This allows prefetching the same relation multiple times with a different
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>; for instance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">vegetarian_pizzas</span> <span class="o">=</span> <span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">vegetarian</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="s1">&#39;menu&#39;</span><span class="p">),</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">vegetarian_pizzas</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="s1">&#39;vegetarian_menu&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>Lookups created with custom <code class="docutils literal notranslate"><span class="pre">to_attr</span></code> can still be traversed as usual by other
lookups:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">vegetarian_pizzas</span> <span class="o">=</span> <span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">vegetarian</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">vegetarian_pizzas</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="s1">&#39;vegetarian_menu&#39;</span><span class="p">),</span>
<span class="gp">... </span>    <span class="s1">&#39;vegetarian_menu__toppings&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Using <code class="docutils literal notranslate"><span class="pre">to_attr</span></code> is recommended when filtering down the prefetch result as it is
less ambiguous than storing a filtered result in the related manager’s cache:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">queryset</span> <span class="o">=</span> <span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">vegetarian</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Recommended:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">restaurants</span> <span class="o">=</span> <span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">queryset</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="s1">&#39;vegetarian_pizzas&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">vegetarian_pizzas</span> <span class="o">=</span> <span class="n">restaurants</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">vegetarian_pizzas</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Not recommended:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">restaurants</span> <span class="o">=</span> <span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">queryset</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">vegetarian_pizzas</span> <span class="o">=</span> <span class="n">restaurants</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">pizzas</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
</pre></div>
</div>
<p>Custom prefetching also works with single related relations like
forward <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> or <code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code>. Generally you’ll want to use
<a class="reference internal" href="#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><code class="xref py py-meth docutils literal notranslate"><span class="pre">select_related()</span></code></a> for these relations, but there are a number of cases
where prefetching with a custom <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> is useful:</p>
<ul>
<li><p class="first">You want to use a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> that performs further prefetching
on related models.</p>
</li>
<li><p class="first">You want to prefetch only a subset of the related objects.</p>
</li>
<li><p class="first">You want to use performance optimization techniques like
<a class="reference internal" href="#django.db.models.query.QuerySet.defer" title="django.db.models.query.QuerySet.defer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">deferred</span> <span class="pre">fields</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">queryset</span> <span class="o">=</span> <span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">restaurants</span> <span class="o">=</span> <span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;best_pizza&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">queryset</span><span class="p">))</span>
</pre></div>
</div>
</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The ordering of lookups matters.</p>
<p>Take the following examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">prefetch_related</span><span class="p">(</span><span class="s1">&#39;pizzas__toppings&#39;</span><span class="p">,</span> <span class="s1">&#39;pizzas&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This works even though it’s unordered because <code class="docutils literal notranslate"><span class="pre">'pizzas__toppings'</span></code>
already contains all the needed information, therefore the second argument
<code class="docutils literal notranslate"><span class="pre">'pizzas'</span></code> is actually redundant.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">prefetch_related</span><span class="p">(</span><span class="s1">&#39;pizzas__toppings&#39;</span><span class="p">,</span> <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()))</span>
</pre></div>
</div>
<p>This will raise a <code class="docutils literal notranslate"><span class="pre">ValueError</span></code> because of the attempt to redefine the
queryset of a previously seen lookup. Note that an implicit queryset was
created to traverse <code class="docutils literal notranslate"><span class="pre">'pizzas'</span></code> as part of the <code class="docutils literal notranslate"><span class="pre">'pizzas__toppings'</span></code>
lookup.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">prefetch_related</span><span class="p">(</span><span class="s1">&#39;pizza_list__toppings&#39;</span><span class="p">,</span> <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="s1">&#39;pizza_list&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>This will trigger an <code class="docutils literal notranslate"><span class="pre">AttributeError</span></code> because <code class="docutils literal notranslate"><span class="pre">'pizza_list'</span></code> doesn’t exist yet
when <code class="docutils literal notranslate"><span class="pre">'pizza_list__toppings'</span></code> is being processed.</p>
<p class="last">This consideration is not limited to the use of <code class="docutils literal notranslate"><span class="pre">Prefetch</span></code> objects. Some
advanced techniques may require that the lookups be performed in a
specific order to avoid creating extra queries; therefore it’s recommended
to always carefully order <code class="docutils literal notranslate"><span class="pre">prefetch_related</span></code> arguments.</p>
</div>
</div>
<div class="section" id="s-extra">
<span id="extra"></span><h4><code class="docutils literal notranslate"><span class="pre">extra()</span></code><a class="headerlink" href="#extra" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.extra">
<code class="descname">extra</code>(<em>select=None</em>, <em>where=None</em>, <em>params=None</em>, <em>tables=None</em>, <em>order_by=None</em>, <em>select_params=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.extra" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Sometimes, the Django query syntax by itself can’t easily express a complex
<code class="docutils literal notranslate"><span class="pre">WHERE</span></code> clause. For these edge cases, Django provides the <code class="docutils literal notranslate"><span class="pre">extra()</span></code>
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> modifier — a hook for injecting specific clauses into the SQL
generated by a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>.</p>
<div class="admonition-use-this-method-as-a-last-resort admonition">
<p class="first admonition-title">Use this method as a last resort</p>
<p>This is an old API that we aim to deprecate at some point in the future.
Use it only if you cannot express your query using other queryset methods.
If you do need to use it, please <a class="reference external" href="https://code.djangoproject.com/newticket">file a ticket</a> using the <a class="reference external" href="https://code.djangoproject.com/query?status=assigned&amp;status=new&amp;keywords=~QuerySet.extra">QuerySet.extra
keyword</a>
with your use case (please check the list of existing tickets first) so
that we can enhance the QuerySet API to allow removing <code class="docutils literal notranslate"><span class="pre">extra()</span></code>. We are
no longer improving or fixing bugs for this method.</p>
<p>For example, this use of <code class="docutils literal notranslate"><span class="pre">extra()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">qs</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">select</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;val&#39;</span><span class="p">:</span> <span class="s2">&quot;select col from sometable where othercol = </span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">},</span>
<span class="gp">... </span>    <span class="n">select_params</span><span class="o">=</span><span class="p">(</span><span class="n">someparam</span><span class="p">,),</span>
<span class="gp">... </span><span class="p">)</span>
</pre></div>
</div>
<p>is equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">qs</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span><span class="n">val</span><span class="o">=</span><span class="n">RawSQL</span><span class="p">(</span><span class="s2">&quot;select col from sometable where othercol = </span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">someparam</span><span class="p">,)))</span>
</pre></div>
</div>
<p class="last">The main benefit of using <a class="reference internal" href="expressions.html#django.db.models.expressions.RawSQL" title="django.db.models.expressions.RawSQL"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawSQL</span></code></a> is
that you can set <code class="docutils literal notranslate"><span class="pre">output_field</span></code> if needed. The main downside is that if
you refer to some table alias of the queryset in the raw SQL, then it is
possible that Django might change that alias (for example, when the
queryset is used as a subquery in yet another query).</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">You should be very careful whenever you use <code class="docutils literal notranslate"><span class="pre">extra()</span></code>. Every time you use
it, you should escape any parameters that the user can control by using
<code class="docutils literal notranslate"><span class="pre">params</span></code> in order to protect against SQL injection attacks . Please
read more about <a class="reference internal" href="../../topics/security.html#sql-injection-protection"><span class="std std-ref">SQL injection protection</span></a>.</p>
</div>
<p>By definition, these extra lookups may not be portable to different database
engines (because you’re explicitly writing SQL code) and violate the DRY
principle, so you should avoid them if possible.</p>
<p>Specify one or more of <code class="docutils literal notranslate"><span class="pre">params</span></code>, <code class="docutils literal notranslate"><span class="pre">select</span></code>, <code class="docutils literal notranslate"><span class="pre">where</span></code> or <code class="docutils literal notranslate"><span class="pre">tables</span></code>. None
of the arguments is required, but you should use at least one of them.</p>
<ul>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">select</span></code></p>
<p>The <code class="docutils literal notranslate"><span class="pre">select</span></code> argument lets you put extra fields in the <code class="docutils literal notranslate"><span class="pre">SELECT</span></code>
clause.  It should be a dictionary mapping attribute names to SQL
clauses to use to calculate that attribute.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">select</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;is_recent&#39;</span><span class="p">:</span> <span class="s2">&quot;pub_date &gt; &#39;2006-01-01&#39;&quot;</span><span class="p">})</span>
</pre></div>
</div>
<p>As a result, each <code class="docutils literal notranslate"><span class="pre">Entry</span></code> object will have an extra attribute,
<code class="docutils literal notranslate"><span class="pre">is_recent</span></code>, a boolean representing whether the entry’s <code class="docutils literal notranslate"><span class="pre">pub_date</span></code>
is greater than Jan. 1, 2006.</p>
<p>Django inserts the given SQL snippet directly into the <code class="docutils literal notranslate"><span class="pre">SELECT</span></code>
statement, so the resulting SQL of the above example would be something
like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="n">blog_entry</span><span class="o">.*</span><span class="p">,</span> <span class="p">(</span><span class="n">pub_date</span> <span class="o">&gt;</span> <span class="s1">&#39;2006-01-01&#39;</span><span class="p">)</span> <span class="n">AS</span> <span class="n">is_recent</span>
<span class="n">FROM</span> <span class="n">blog_entry</span><span class="p">;</span>
</pre></div>
</div>
<p>The next example is more advanced; it does a subquery to give each
resulting <code class="docutils literal notranslate"><span class="pre">Blog</span></code> object an <code class="docutils literal notranslate"><span class="pre">entry_count</span></code> attribute, an integer count
of associated <code class="docutils literal notranslate"><span class="pre">Entry</span></code> objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span>
    <span class="n">select</span><span class="o">=</span><span class="p">{</span>
        <span class="s1">&#39;entry_count&#39;</span><span class="p">:</span> <span class="s1">&#39;SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id&#39;</span>
    <span class="p">},</span>
<span class="p">)</span>
</pre></div>
</div>
<p>In this particular case, we’re exploiting the fact that the query will
already contain the <code class="docutils literal notranslate"><span class="pre">blog_blog</span></code> table in its <code class="docutils literal notranslate"><span class="pre">FROM</span></code> clause.</p>
<p>The resulting SQL of the above example would be:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="n">blog_blog</span><span class="o">.*</span><span class="p">,</span> <span class="p">(</span><span class="n">SELECT</span> <span class="n">COUNT</span><span class="p">(</span><span class="o">*</span><span class="p">)</span> <span class="n">FROM</span> <span class="n">blog_entry</span> <span class="n">WHERE</span> <span class="n">blog_entry</span><span class="o">.</span><span class="n">blog_id</span> <span class="o">=</span> <span class="n">blog_blog</span><span class="o">.</span><span class="n">id</span><span class="p">)</span> <span class="n">AS</span> <span class="n">entry_count</span>
<span class="n">FROM</span> <span class="n">blog_blog</span><span class="p">;</span>
</pre></div>
</div>
<p>Note that the parentheses required by most database engines around
subqueries are not required in Django’s <code class="docutils literal notranslate"><span class="pre">select</span></code> clauses. Also note
that some database backends, such as some MySQL versions, don’t support
subqueries.</p>
<p>In some rare cases, you might wish to pass parameters to the SQL
fragments in <code class="docutils literal notranslate"><span class="pre">extra(select=...)</span></code>. For this purpose, use the
<code class="docutils literal notranslate"><span class="pre">select_params</span></code> parameter. Since <code class="docutils literal notranslate"><span class="pre">select_params</span></code> is a sequence and
the <code class="docutils literal notranslate"><span class="pre">select</span></code> attribute is a dictionary, some care is required so that
the parameters are matched up correctly with the extra select pieces.
In this situation, you should use a <a class="reference external" href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" title="(in Python v3.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.OrderedDict</span></code></a> for
the <code class="docutils literal notranslate"><span class="pre">select</span></code> value, not just a normal Python dictionary.</p>
<p>This will work, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span>
    <span class="n">select</span><span class="o">=</span><span class="n">OrderedDict</span><span class="p">([(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">)]),</span>
    <span class="n">select_params</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;one&#39;</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>If you need to use a literal <code class="docutils literal notranslate"><span class="pre">%s</span></code> inside your select string, use
the sequence <code class="docutils literal notranslate"><span class="pre">%%s</span></code>.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">where</span></code> / <code class="docutils literal notranslate"><span class="pre">tables</span></code></p>
<p>You can define explicit SQL <code class="docutils literal notranslate"><span class="pre">WHERE</span></code> clauses — perhaps to perform
non-explicit joins — by using <code class="docutils literal notranslate"><span class="pre">where</span></code>. You can manually add tables to
the SQL <code class="docutils literal notranslate"><span class="pre">FROM</span></code> clause by using <code class="docutils literal notranslate"><span class="pre">tables</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">where</span></code> and <code class="docutils literal notranslate"><span class="pre">tables</span></code> both take a list of strings. All <code class="docutils literal notranslate"><span class="pre">where</span></code>
parameters are “AND”ed to any other search criteria.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">where</span><span class="o">=</span><span class="p">[</span><span class="s2">&quot;foo=&#39;a&#39; OR bar = &#39;a&#39;&quot;</span><span class="p">,</span> <span class="s2">&quot;baz = &#39;a&#39;&quot;</span><span class="p">])</span>
</pre></div>
</div>
<p>…translates (roughly) into the following SQL:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">*</span> <span class="n">FROM</span> <span class="n">blog_entry</span> <span class="n">WHERE</span> <span class="p">(</span><span class="n">foo</span><span class="o">=</span><span class="s1">&#39;a&#39;</span> <span class="n">OR</span> <span class="n">bar</span><span class="o">=</span><span class="s1">&#39;a&#39;</span><span class="p">)</span> <span class="n">AND</span> <span class="p">(</span><span class="n">baz</span><span class="o">=</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Be careful when using the <code class="docutils literal notranslate"><span class="pre">tables</span></code> parameter if you’re specifying
tables that are already used in the query. When you add extra tables
via the <code class="docutils literal notranslate"><span class="pre">tables</span></code> parameter, Django assumes you want that table
included an extra time, if it is already included. That creates a
problem, since the table name will then be given an alias. If a table
appears multiple times in an SQL statement, the second and subsequent
occurrences must use aliases so the database can tell them apart. If
you’re referring to the extra table you added in the extra <code class="docutils literal notranslate"><span class="pre">where</span></code>
parameter this is going to cause errors.</p>
<p>Normally you’ll only be adding extra tables that don’t already appear
in the query. However, if the case outlined above does occur, there are
a few solutions. First, see if you can get by without including the
extra table and use the one already in the query. If that isn’t
possible, put your <code class="docutils literal notranslate"><span class="pre">extra()</span></code> call at the front of the queryset
construction so that your table is the first use of that table.
Finally, if all else fails, look at the query produced and rewrite your
<code class="docutils literal notranslate"><span class="pre">where</span></code> addition to use the alias given to your extra table. The
alias will be the same each time you construct the queryset in the same
way, so you can rely upon the alias name to not change.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">order_by</span></code></p>
<p>If you need to order the resulting queryset using some of the new
fields or tables you have included via <code class="docutils literal notranslate"><span class="pre">extra()</span></code> use the <code class="docutils literal notranslate"><span class="pre">order_by</span></code>
parameter to <code class="docutils literal notranslate"><span class="pre">extra()</span></code> and pass in a sequence of strings. These
strings should either be model fields (as in the normal
<a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><code class="xref py py-meth docutils literal notranslate"><span class="pre">order_by()</span></code></a> method on querysets), of the form
<code class="docutils literal notranslate"><span class="pre">table_name.column_name</span></code> or an alias for a column that you specified
in the <code class="docutils literal notranslate"><span class="pre">select</span></code> parameter to <code class="docutils literal notranslate"><span class="pre">extra()</span></code>.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">q</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">select</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;is_recent&#39;</span><span class="p">:</span> <span class="s2">&quot;pub_date &gt; &#39;2006-01-01&#39;&quot;</span><span class="p">})</span>
<span class="n">q</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">order_by</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;-is_recent&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>This would sort all the items for which <code class="docutils literal notranslate"><span class="pre">is_recent</span></code> is true to the
front of the result set (<code class="docutils literal notranslate"><span class="pre">True</span></code> sorts before <code class="docutils literal notranslate"><span class="pre">False</span></code> in a
descending ordering).</p>
<p>This shows, by the way, that you can make multiple calls to <code class="docutils literal notranslate"><span class="pre">extra()</span></code>
and it will behave as you expect (adding new constraints each time).</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">params</span></code></p>
<p>The <code class="docutils literal notranslate"><span class="pre">where</span></code> parameter described above may use standard Python
database string placeholders — <code class="docutils literal notranslate"><span class="pre">'%s'</span></code> to indicate parameters the
database engine should automatically quote. The <code class="docutils literal notranslate"><span class="pre">params</span></code> argument is
a list of any extra parameters to be substituted.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">where</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;headline=</span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">],</span> <span class="n">params</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;Lennon&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>Always use <code class="docutils literal notranslate"><span class="pre">params</span></code> instead of embedding values directly into
<code class="docutils literal notranslate"><span class="pre">where</span></code> because <code class="docutils literal notranslate"><span class="pre">params</span></code> will ensure values are quoted correctly
according to your particular backend. For example, quotes will be
escaped correctly.</p>
<p>Bad:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">where</span><span class="o">=</span><span class="p">[</span><span class="s2">&quot;headline=&#39;Lennon&#39;&quot;</span><span class="p">])</span>
</pre></div>
</div>
<p>Good:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">where</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;headline=</span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">],</span> <span class="n">params</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;Lennon&#39;</span><span class="p">])</span>
</pre></div>
</div>
</li>
</ul>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">If you are performing queries on MySQL, note that MySQL’s silent type coercion
may cause unexpected results when mixing types. If you query on a string
type column, but with an integer value, MySQL will coerce the types of all values
in the table to an integer before performing the comparison. For example, if your
table contains the values <code class="docutils literal notranslate"><span class="pre">'abc'</span></code>, <code class="docutils literal notranslate"><span class="pre">'def'</span></code> and you query for <code class="docutils literal notranslate"><span class="pre">WHERE</span> <span class="pre">mycolumn=0</span></code>,
both rows will match. To prevent this, perform the correct typecasting
before using the value in a query.</p>
</div>
</div>
<div class="section" id="s-defer">
<span id="defer"></span><h4><code class="docutils literal notranslate"><span class="pre">defer()</span></code><a class="headerlink" href="#defer" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.defer">
<code class="descname">defer</code>(<em>*fields</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.defer" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>In some complex data-modeling situations, your models might contain a lot of
fields, some of which could contain a lot of data (for example, text fields),
or require expensive processing to convert them to Python objects. If you are
using the results of a queryset in some situation where you don’t know
if you need those particular fields when you initially fetch the data, you can
tell Django not to retrieve them from the database.</p>
<p>This is done by passing the names of the fields to not load to <code class="docutils literal notranslate"><span class="pre">defer()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s2">&quot;headline&quot;</span><span class="p">,</span> <span class="s2">&quot;body&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>A queryset that has deferred fields will still return model instances. Each
deferred field will be retrieved from the database if you access that field
(one at a time, not all the deferred fields at once).</p>
<p>You can make multiple calls to <code class="docutils literal notranslate"><span class="pre">defer()</span></code>. Each call adds new fields to the
deferred set:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Defers both the body and headline fields.</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s2">&quot;body&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">rating</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s2">&quot;headline&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The order in which fields are added to the deferred set does not matter.
Calling <code class="docutils literal notranslate"><span class="pre">defer()</span></code> with a field name that has already been deferred is
harmless (the field will still be deferred).</p>
<p>You can defer loading of fields in related models (if the related models are
loading via <a class="reference internal" href="#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><code class="xref py py-meth docutils literal notranslate"><span class="pre">select_related()</span></code></a>) by using the standard double-underscore
notation to separate related fields:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">()</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s2">&quot;entry__headline&quot;</span><span class="p">,</span> <span class="s2">&quot;entry__body&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you want to clear the set of deferred fields, pass <code class="docutils literal notranslate"><span class="pre">None</span></code> as a parameter
to <code class="docutils literal notranslate"><span class="pre">defer()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Load all fields immediately.</span>
<span class="n">my_queryset</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>Some fields in a model won’t be deferred, even if you ask for them. You can
never defer the loading of the primary key. If you are using
<a class="reference internal" href="#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><code class="xref py py-meth docutils literal notranslate"><span class="pre">select_related()</span></code></a> to retrieve related models, you shouldn’t defer the
loading of the field that connects from the primary model to the related
one, doing so will result in an error.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The <code class="docutils literal notranslate"><span class="pre">defer()</span></code> method (and its cousin, <a class="reference internal" href="#django.db.models.query.QuerySet.only" title="django.db.models.query.QuerySet.only"><code class="xref py py-meth docutils literal notranslate"><span class="pre">only()</span></code></a>, below) are only for
advanced use-cases. They provide an optimization for when you have analyzed
your queries closely and understand <em>exactly</em> what information you need and
have measured that the difference between returning the fields you need and
the full set of fields for the model will be significant.</p>
<p>Even if you think you are in the advanced use-case situation, <strong>only use
defer() when you cannot, at queryset load time, determine if you will need
the extra fields or not</strong>. If you are frequently loading and using a
particular subset of your data, the best choice you can make is to
normalize your models and put the non-loaded data into a separate model
(and database table). If the columns <em>must</em> stay in the one table for some
reason, create a model with <code class="docutils literal notranslate"><span class="pre">Meta.managed</span> <span class="pre">=</span> <span class="pre">False</span></code> (see the
<a class="reference internal" href="options.html#django.db.models.Options.managed" title="django.db.models.Options.managed"><code class="xref py py-attr docutils literal notranslate"><span class="pre">managed</span> <span class="pre">attribute</span></code></a> documentation)
containing just the fields you normally need to load and use that where you
might otherwise call <code class="docutils literal notranslate"><span class="pre">defer()</span></code>. This makes your code more explicit to the
reader, is slightly faster and consumes a little less memory in the Python
process.</p>
<p>For example, both of these models use the same underlying database table:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">CommonlyUsedModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">f1</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">managed</span> <span class="o">=</span> <span class="kc">False</span>
        <span class="n">db_table</span> <span class="o">=</span> <span class="s1">&#39;app_largetable&#39;</span>

<span class="k">class</span> <span class="nc">ManagedModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">f1</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
    <span class="n">f2</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">db_table</span> <span class="o">=</span> <span class="s1">&#39;app_largetable&#39;</span>

<span class="c1"># Two equivalent QuerySets:</span>
<span class="n">CommonlyUsedModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="n">ManagedModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s1">&#39;f2&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p class="last">If many fields need to be duplicated in the unmanaged model, it may be best
to create an abstract model with the shared fields and then have the
unmanaged and managed models inherit from the abstract model.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When calling <a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> for instances with
deferred fields, only the loaded fields will be saved. See
<a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> for more details.</p>
</div>
</div>
<div class="section" id="s-only">
<span id="only"></span><h4><code class="docutils literal notranslate"><span class="pre">only()</span></code><a class="headerlink" href="#only" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.only">
<code class="descname">only</code>(<em>*fields</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.only" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>The <code class="docutils literal notranslate"><span class="pre">only()</span></code> method is more or less the opposite of <a class="reference internal" href="#django.db.models.query.QuerySet.defer" title="django.db.models.query.QuerySet.defer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">defer()</span></code></a>. You call
it with the fields that should <em>not</em> be deferred when retrieving a model.  If
you have a model where almost all the fields need to be deferred, using
<code class="docutils literal notranslate"><span class="pre">only()</span></code> to specify the complementary set of fields can result in simpler
code.</p>
<p>Suppose you have a model with fields <code class="docutils literal notranslate"><span class="pre">name</span></code>, <code class="docutils literal notranslate"><span class="pre">age</span></code> and <code class="docutils literal notranslate"><span class="pre">biography</span></code>. The
following two querysets are the same, in terms of deferred fields:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s2">&quot;age&quot;</span><span class="p">,</span> <span class="s2">&quot;biography&quot;</span><span class="p">)</span>
<span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s2">&quot;name&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Whenever you call <code class="docutils literal notranslate"><span class="pre">only()</span></code> it <em>replaces</em> the set of fields to load
immediately. The method’s name is mnemonic: <strong>only</strong> those fields are loaded
immediately; the remainder are deferred. Thus, successive calls to <code class="docutils literal notranslate"><span class="pre">only()</span></code>
result in only the final fields being considered:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># This will defer all fields except the headline.</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s2">&quot;body&quot;</span><span class="p">,</span> <span class="s2">&quot;rating&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s2">&quot;headline&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Since <code class="docutils literal notranslate"><span class="pre">defer()</span></code> acts incrementally (adding fields to the deferred list), you
can combine calls to <code class="docutils literal notranslate"><span class="pre">only()</span></code> and <code class="docutils literal notranslate"><span class="pre">defer()</span></code> and things will behave
logically:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Final result is that everything except &quot;headline&quot; is deferred.</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s2">&quot;headline&quot;</span><span class="p">,</span> <span class="s2">&quot;body&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s2">&quot;body&quot;</span><span class="p">)</span>

<span class="c1"># Final result loads headline and body immediately (only() replaces any</span>
<span class="c1"># existing set of fields).</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s2">&quot;body&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s2">&quot;headline&quot;</span><span class="p">,</span> <span class="s2">&quot;body&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>All of the cautions in the note for the <a class="reference internal" href="#django.db.models.query.QuerySet.defer" title="django.db.models.query.QuerySet.defer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">defer()</span></code></a> documentation apply to
<code class="docutils literal notranslate"><span class="pre">only()</span></code> as well. Use it cautiously and only after exhausting your other
options.</p>
<p>Using <a class="reference internal" href="#django.db.models.query.QuerySet.only" title="django.db.models.query.QuerySet.only"><code class="xref py py-meth docutils literal notranslate"><span class="pre">only()</span></code></a> and omitting a field requested using <a class="reference internal" href="#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><code class="xref py py-meth docutils literal notranslate"><span class="pre">select_related()</span></code></a>
is an error as well.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When calling <a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> for instances with
deferred fields, only the loaded fields will be saved. See
<a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> for more details.</p>
</div>
</div>
<div class="section" id="s-using">
<span id="using"></span><h4><code class="docutils literal notranslate"><span class="pre">using()</span></code><a class="headerlink" href="#using" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.using">
<code class="descname">using</code>(<em>alias</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.using" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>This method is for controlling which database the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> will be
evaluated against if you are using more than one database.  The only argument
this method takes is the alias of a database, as defined in
<a class="reference internal" href="../settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a>.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># queries the database with the &#39;default&#39; alias.</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>

<span class="c1"># queries the database with the &#39;backup&#39; alias</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">using</span><span class="p">(</span><span class="s1">&#39;backup&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-select-for-update">
<span id="select-for-update"></span><h4><code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code><a class="headerlink" href="#select-for-update" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.select_for_update">
<code class="descname">select_for_update</code>(<em>nowait=False</em>, <em>skip_locked=False</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.select_for_update" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a queryset that will lock rows until the end of the transaction,
generating a <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">...</span> <span class="pre">FOR</span> <span class="pre">UPDATE</span></code> SQL statement on supported databases.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_for_update</span><span class="p">()</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">author</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="p">)</span>
</pre></div>
</div>
<p>All matched entries will be locked until the end of the transaction block,
meaning that other transactions will be prevented from changing or acquiring
locks on them.</p>
<p>Usually, if another transaction has already acquired a lock on one of the
selected rows, the query will block until the lock is released. If this is
not the behavior you want, call <code class="docutils literal notranslate"><span class="pre">select_for_update(nowait=True)</span></code>. This will
make the call non-blocking. If a conflicting lock is already acquired by
another transaction, <a class="reference internal" href="../exceptions.html#django.db.DatabaseError" title="django.db.DatabaseError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DatabaseError</span></code></a> will be raised when the
queryset is evaluated. You can also ignore locked rows by using
<code class="docutils literal notranslate"><span class="pre">select_for_update(skip_locked=True)</span></code> instead. The <code class="docutils literal notranslate"><span class="pre">nowait</span></code> and
<code class="docutils literal notranslate"><span class="pre">skip_locked</span></code> are mutually exclusive and attempts to call
<code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code> with both options enabled will result in a
<a class="reference external" href="https://docs.python.org/3/library/exceptions.html#ValueError" title="(in Python v3.7)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
<p>Currently, the <code class="docutils literal notranslate"><span class="pre">postgresql</span></code>, <code class="docutils literal notranslate"><span class="pre">oracle</span></code>, and <code class="docutils literal notranslate"><span class="pre">mysql</span></code> database
backends support <code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code>. However, MySQL doesn’t support the
<code class="docutils literal notranslate"><span class="pre">nowait</span></code> and <code class="docutils literal notranslate"><span class="pre">skip_locked</span></code> arguments.</p>
<p>Passing <code class="docutils literal notranslate"><span class="pre">nowait=True</span></code> or <code class="docutils literal notranslate"><span class="pre">skip_locked=True</span></code> to <code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code>
using database backends that do not support these options, such as MySQL, will
cause a <a class="reference internal" href="../exceptions.html#django.db.DatabaseError" title="django.db.DatabaseError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DatabaseError</span></code></a> to be raised. This prevents code from
unexpectedly blocking.</p>
<p>Evaluating a queryset with <code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code> in autocommit mode on
backends which support <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">...</span> <span class="pre">FOR</span> <span class="pre">UPDATE</span></code> is a
<a class="reference internal" href="../exceptions.html#django.db.transaction.TransactionManagementError" title="django.db.transaction.TransactionManagementError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TransactionManagementError</span></code></a> error because the
rows are not locked in that case. If allowed, this would facilitate data
corruption and could easily be caused by calling code that expects to be run in
a transaction outside of one.</p>
<p>Using <code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code> on backends which do not support
<code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">...</span> <span class="pre">FOR</span> <span class="pre">UPDATE</span></code> (such as SQLite) will have no effect.
<code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">...</span> <span class="pre">FOR</span> <span class="pre">UPDATE</span></code> will not be added to the query, and an error isn’t
raised if <code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code> is used in autocommit mode.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Although <code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code> normally fails in autocommit mode, since
<a class="reference internal" href="../../topics/testing/tools.html#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> automatically wraps each test in a
transaction, calling <code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code> in a <code class="docutils literal notranslate"><span class="pre">TestCase</span></code> even outside
an <a class="reference internal" href="../../topics/db/transactions.html#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> block will (perhaps unexpectedly)
pass without raising a <code class="docutils literal notranslate"><span class="pre">TransactionManagementError</span></code>. To properly test
<code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code> you should use
<a class="reference internal" href="../../topics/testing/tools.html#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TransactionTestCase</span></code></a>.</p>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 1.11:</span> <p>The <code class="docutils literal notranslate"><span class="pre">skip_locked</span></code> argument was added.</p>
</div>
</div>
<div class="section" id="s-raw">
<span id="raw"></span><h4><code class="docutils literal notranslate"><span class="pre">raw()</span></code><a class="headerlink" href="#raw" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.raw">
<code class="descname">raw</code>(<em>raw_query</em>, <em>params=None</em>, <em>translations=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.raw" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Takes a raw SQL query, executes it, and returns a
<code class="docutils literal notranslate"><span class="pre">django.db.models.query.RawQuerySet</span></code> instance. This <code class="docutils literal notranslate"><span class="pre">RawQuerySet</span></code> instance
can be iterated over just like an normal <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> to provide object instances.</p>
<p>See the <a class="reference internal" href="../../topics/db/sql.html"><span class="doc">Performing raw SQL queries</span></a> for more information.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">raw()</span></code> always triggers a new query and doesn’t account for previous
filtering. As such, it should generally be called from the <code class="docutils literal notranslate"><span class="pre">Manager</span></code> or
from a fresh <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> instance.</p>
</div>
</div>
</div>
<div class="section" id="s-methods-that-do-not-return-querysets">
<span id="methods-that-do-not-return-querysets"></span><h3>Methods that do not return <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s<a class="headerlink" href="#methods-that-do-not-return-querysets" title="Permalink to this headline">¶</a></h3>
<p>The following <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> methods evaluate the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> and return
something <em>other than</em> a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>.</p>
<p>These methods do not use a cache (see <a class="reference internal" href="../../topics/db/queries.html#caching-and-querysets"><span class="std std-ref">Caching and QuerySets</span></a>). Rather,
they query the database each time they’re called.</p>
<div class="section" id="s-get">
<span id="get"></span><h4><code class="docutils literal notranslate"><span class="pre">get()</span></code><a class="headerlink" href="#get" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.get">
<code class="descname">get</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.get" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns the object matching the given lookup parameters, which should be in
the format described in <a class="reference internal" href="#id4">Field lookups</a>.</p>
<p><code class="docutils literal notranslate"><span class="pre">get()</span></code> raises <a class="reference internal" href="../exceptions.html#django.core.exceptions.MultipleObjectsReturned" title="django.core.exceptions.MultipleObjectsReturned"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MultipleObjectsReturned</span></code></a> if more
than one object was found. The
<a class="reference internal" href="../exceptions.html#django.core.exceptions.MultipleObjectsReturned" title="django.core.exceptions.MultipleObjectsReturned"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MultipleObjectsReturned</span></code></a> exception is an
attribute of the model class.</p>
<p><code class="docutils literal notranslate"><span class="pre">get()</span></code> raises a <a class="reference internal" href="instances.html#django.db.models.Model.DoesNotExist" title="django.db.models.Model.DoesNotExist"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DoesNotExist</span></code></a> exception if an
object wasn’t found for the given parameters. This exception is an attribute
of the model class. Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span> <span class="c1"># raises Entry.DoesNotExist</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="instances.html#django.db.models.Model.DoesNotExist" title="django.db.models.Model.DoesNotExist"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DoesNotExist</span></code></a> exception inherits from
<a class="reference internal" href="../exceptions.html#django.core.exceptions.ObjectDoesNotExist" title="django.core.exceptions.ObjectDoesNotExist"><code class="xref py py-exc docutils literal notranslate"><span class="pre">django.core.exceptions.ObjectDoesNotExist</span></code></a>, so you can target multiple
<a class="reference internal" href="instances.html#django.db.models.Model.DoesNotExist" title="django.db.models.Model.DoesNotExist"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DoesNotExist</span></code></a> exceptions. Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.exceptions</span> <span class="k">import</span> <span class="n">ObjectDoesNotExist</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
    <span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="k">except</span> <span class="n">ObjectDoesNotExist</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Either the entry or blog doesn&#39;t exist.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you expect a queryset to return one row, you can use <code class="docutils literal notranslate"><span class="pre">get()</span></code> without any
arguments to return the object for that row:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">entry</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="o">...</span><span class="p">)</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="o">...</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="s-create">
<span id="create"></span><h4><code class="docutils literal notranslate"><span class="pre">create()</span></code><a class="headerlink" href="#create" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.create">
<code class="descname">create</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.create" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>A convenience method for creating an object and saving it all in one step.  Thus:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s2">&quot;Bruce&quot;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s2">&quot;Springsteen&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>and:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span> <span class="o">=</span> <span class="n">Person</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s2">&quot;Bruce&quot;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s2">&quot;Springsteen&quot;</span><span class="p">)</span>
<span class="n">p</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">force_insert</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>are equivalent.</p>
<p>The <a class="reference internal" href="instances.html#ref-models-force-insert"><span class="std std-ref">force_insert</span></a> parameter is documented
elsewhere, but all it means is that a new object will always be created.
Normally you won’t need to worry about this. However, if your model contains a
manual primary key value that you set and if that value already exists in the
database, a call to <code class="docutils literal notranslate"><span class="pre">create()</span></code> will fail with an
<a class="reference internal" href="../exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IntegrityError</span></code></a> since primary keys must be unique. Be
prepared to handle the exception if you are using manual primary keys.</p>
</div>
<div class="section" id="s-get-or-create">
<span id="get-or-create"></span><h4><code class="docutils literal notranslate"><span class="pre">get_or_create()</span></code><a class="headerlink" href="#get-or-create" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.get_or_create">
<code class="descname">get_or_create</code>(<em>defaults=None</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.get_or_create" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>A convenience method for looking up an object with the given <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> (may be
empty if your model has defaults for all fields), creating one if necessary.</p>
<p>Returns a tuple of <code class="docutils literal notranslate"><span class="pre">(object,</span> <span class="pre">created)</span></code>, where <code class="docutils literal notranslate"><span class="pre">object</span></code> is the retrieved or
created object and <code class="docutils literal notranslate"><span class="pre">created</span></code> is a boolean specifying whether a new object was
created.</p>
<p>This is meant as a shortcut to boilerplatish code. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">obj</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
<span class="k">except</span> <span class="n">Person</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span>
    <span class="n">obj</span> <span class="o">=</span> <span class="n">Person</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">,</span> <span class="n">birthday</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">1940</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">9</span><span class="p">))</span>
    <span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>This pattern gets quite unwieldy as the number of fields in a model goes up.
The above example can be rewritten using <code class="docutils literal notranslate"><span class="pre">get_or_create()</span></code> like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">obj</span><span class="p">,</span> <span class="n">created</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span>
    <span class="n">first_name</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">,</span>
    <span class="n">last_name</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">,</span>
    <span class="n">defaults</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;birthday&#39;</span><span class="p">:</span> <span class="n">date</span><span class="p">(</span><span class="mi">1940</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">9</span><span class="p">)},</span>
<span class="p">)</span>
</pre></div>
</div>
<p>Any keyword arguments passed to <code class="docutils literal notranslate"><span class="pre">get_or_create()</span></code> — <em>except</em> an optional one
called <code class="docutils literal notranslate"><span class="pre">defaults</span></code> — will be used in a <a class="reference internal" href="#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> call. If an object is
found, <code class="docutils literal notranslate"><span class="pre">get_or_create()</span></code> returns a tuple of that object and <code class="docutils literal notranslate"><span class="pre">False</span></code>. If
multiple objects are found, <code class="docutils literal notranslate"><span class="pre">get_or_create</span></code> raises
<a class="reference internal" href="../exceptions.html#django.core.exceptions.MultipleObjectsReturned" title="django.core.exceptions.MultipleObjectsReturned"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MultipleObjectsReturned</span></code></a>. If an object is <em>not</em>
found, <code class="docutils literal notranslate"><span class="pre">get_or_create()</span></code> will instantiate and save a new object, returning a
tuple of the new object and <code class="docutils literal notranslate"><span class="pre">True</span></code>. The new object will be created roughly
according to this algorithm:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">params</span> <span class="o">=</span> <span class="p">{</span><span class="n">k</span><span class="p">:</span> <span class="n">v</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="k">if</span> <span class="s1">&#39;__&#39;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">k</span><span class="p">}</span>
<span class="n">params</span><span class="o">.</span><span class="n">update</span><span class="p">({</span><span class="n">k</span><span class="p">:</span> <span class="n">v</span><span class="p">()</span> <span class="k">if</span> <span class="n">callable</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="k">else</span> <span class="n">v</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">defaults</span><span class="o">.</span><span class="n">items</span><span class="p">()})</span>
<span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">params</span><span class="p">)</span>
<span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>In English, that means start with any non-<code class="docutils literal notranslate"><span class="pre">'defaults'</span></code> keyword argument that
doesn’t contain a double underscore (which would indicate a non-exact lookup).
Then add the contents of <code class="docutils literal notranslate"><span class="pre">defaults</span></code>, overriding any keys if necessary, and
use the result as the keyword arguments to the model class. If there are any
callables in <code class="docutils literal notranslate"><span class="pre">defaults</span></code>, evaluate them. As hinted at above, this is a
simplification of the algorithm that is used, but it contains all the pertinent
details. The internal implementation has some more error-checking than this and
handles some extra edge-conditions; if you’re interested, read the code.</p>
<p>If you have a field named <code class="docutils literal notranslate"><span class="pre">defaults</span></code> and want to use it as an exact lookup in
<code class="docutils literal notranslate"><span class="pre">get_or_create()</span></code>, just use <code class="docutils literal notranslate"><span class="pre">'defaults__exact'</span></code>, like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Foo</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">defaults__exact</span><span class="o">=</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">defaults</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;defaults&#39;</span><span class="p">:</span> <span class="s1">&#39;baz&#39;</span><span class="p">})</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">get_or_create()</span></code> method has similar error behavior to <a class="reference internal" href="#django.db.models.query.QuerySet.create" title="django.db.models.query.QuerySet.create"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create()</span></code></a>
when you’re using manually specified primary keys. If an object needs to be
created and the key already exists in the database, an
<a class="reference internal" href="../exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IntegrityError</span></code></a> will be raised.</p>
<p>This method is atomic assuming correct usage, correct database configuration,
and correct behavior of the underlying database. However, if uniqueness is not
enforced at the database level for the <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> used in a <code class="docutils literal notranslate"><span class="pre">get_or_create</span></code>
call (see <a class="reference internal" href="fields.html#django.db.models.Field.unique" title="django.db.models.Field.unique"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique</span></code></a> or
<a class="reference internal" href="options.html#django.db.models.Options.unique_together" title="django.db.models.Options.unique_together"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique_together</span></code></a>), this method is prone to a
race-condition which can result in multiple rows with the same parameters being
inserted simultaneously.</p>
<p>If you are using MySQL, be sure to use the <code class="docutils literal notranslate"><span class="pre">READ</span> <span class="pre">COMMITTED</span></code> isolation level
rather than <code class="docutils literal notranslate"><span class="pre">REPEATABLE</span> <span class="pre">READ</span></code> (the default), otherwise you may see cases
where <code class="docutils literal notranslate"><span class="pre">get_or_create</span></code> will raise an <a class="reference internal" href="../exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IntegrityError</span></code></a> but the
object won’t appear in a subsequent <a class="reference internal" href="#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>
call.</p>
<p>Finally, a word on using <code class="docutils literal notranslate"><span class="pre">get_or_create()</span></code> in Django views. Please make sure
to use it only in <code class="docutils literal notranslate"><span class="pre">POST</span></code> requests unless you have a good reason not to.
<code class="docutils literal notranslate"><span class="pre">GET</span></code> requests shouldn’t have any effect on data. Instead, use <code class="docutils literal notranslate"><span class="pre">POST</span></code>
whenever a request to a page has a side effect on your data. For more, see
<span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7231.html#section-4.2.1"><strong>Safe methods</strong></a> in the HTTP spec.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>You can use <code class="docutils literal notranslate"><span class="pre">get_or_create()</span></code> through <a class="reference internal" href="fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a>
attributes and reverse relations. In that case you will restrict the queries
inside the context of that relation. That could lead you to some integrity
problems if you don’t use it consistently.</p>
<p>Being the following models:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Chapter</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">title</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">title</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">256</span><span class="p">)</span>
    <span class="n">chapters</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Chapter</span><span class="p">)</span>
</pre></div>
</div>
<p>You can use <code class="docutils literal notranslate"><span class="pre">get_or_create()</span></code> through Book’s chapters field, but it only
fetches inside the context of that book:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">book</span> <span class="o">=</span> <span class="n">Book</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s2">&quot;Ulysses&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">book</span><span class="o">.</span><span class="n">chapters</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s2">&quot;Telemachus&quot;</span><span class="p">)</span>
<span class="go">(&lt;Chapter: Telemachus&gt;, True)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">book</span><span class="o">.</span><span class="n">chapters</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s2">&quot;Telemachus&quot;</span><span class="p">)</span>
<span class="go">(&lt;Chapter: Telemachus&gt;, False)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Chapter</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s2">&quot;Chapter 1&quot;</span><span class="p">)</span>
<span class="go">&lt;Chapter: Chapter 1&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">book</span><span class="o">.</span><span class="n">chapters</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s2">&quot;Chapter 1&quot;</span><span class="p">)</span>
<span class="go"># Raises IntegrityError</span>
</pre></div>
</div>
<p class="last">This is happening because it’s trying to get or create “Chapter 1” through the
book “Ulysses”, but it can’t do any of them: the relation can’t fetch that
chapter because it isn’t related to that book, but it can’t create it either
because <code class="docutils literal notranslate"><span class="pre">title</span></code> field should be unique.</p>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 1.11:</span> <p>Added support for callable values in <code class="docutils literal notranslate"><span class="pre">defaults</span></code>.</p>
</div>
</div>
<div class="section" id="s-update-or-create">
<span id="update-or-create"></span><h4><code class="docutils literal notranslate"><span class="pre">update_or_create()</span></code><a class="headerlink" href="#update-or-create" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.update_or_create">
<code class="descname">update_or_create</code>(<em>defaults=None</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.update_or_create" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>A convenience method for updating an object with the given <code class="docutils literal notranslate"><span class="pre">kwargs</span></code>, creating
a new one if necessary. The <code class="docutils literal notranslate"><span class="pre">defaults</span></code> is a dictionary of (field, value)
pairs used to update the object. The values in <code class="docutils literal notranslate"><span class="pre">defaults</span></code> can be callables.</p>
<p>Returns a tuple of <code class="docutils literal notranslate"><span class="pre">(object,</span> <span class="pre">created)</span></code>, where <code class="docutils literal notranslate"><span class="pre">object</span></code> is the created or
updated object and <code class="docutils literal notranslate"><span class="pre">created</span></code> is a boolean specifying whether a new object was
created.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">update_or_create</span></code> method tries to fetch an object from database based on
the given <code class="docutils literal notranslate"><span class="pre">kwargs</span></code>. If a match is found, it updates the fields passed in the
<code class="docutils literal notranslate"><span class="pre">defaults</span></code> dictionary.</p>
<p>This is meant as a shortcut to boilerplatish code. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">defaults</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;first_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">}</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">obj</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">defaults</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
        <span class="nb">setattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
    <span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="k">except</span> <span class="n">Person</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span>
    <span class="n">new_values</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;first_name&#39;</span><span class="p">:</span> <span class="s1">&#39;John&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Lennon&#39;</span><span class="p">}</span>
    <span class="n">new_values</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">defaults</span><span class="p">)</span>
    <span class="n">obj</span> <span class="o">=</span> <span class="n">Person</span><span class="p">(</span><span class="o">**</span><span class="n">new_values</span><span class="p">)</span>
    <span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>This pattern gets quite unwieldy as the number of fields in a model goes up.
The above example can be rewritten using <code class="docutils literal notranslate"><span class="pre">update_or_create()</span></code> like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">obj</span><span class="p">,</span> <span class="n">created</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">update_or_create</span><span class="p">(</span>
    <span class="n">first_name</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">,</span>
    <span class="n">defaults</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;first_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">},</span>
<span class="p">)</span>
</pre></div>
</div>
<p>For detailed description how names passed in <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> are resolved see
<a class="reference internal" href="#django.db.models.query.QuerySet.get_or_create" title="django.db.models.query.QuerySet.get_or_create"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_or_create()</span></code></a>.</p>
<p>As described above in <a class="reference internal" href="#django.db.models.query.QuerySet.get_or_create" title="django.db.models.query.QuerySet.get_or_create"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_or_create()</span></code></a>, this method is prone to a
race-condition which can result in multiple rows being inserted simultaneously
if uniqueness is not enforced at the database level.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.11:</span> <p>Added support for callable values in <code class="docutils literal notranslate"><span class="pre">defaults</span></code>.</p>
</div>
</div>
<div class="section" id="s-bulk-create">
<span id="bulk-create"></span><h4><code class="docutils literal notranslate"><span class="pre">bulk_create()</span></code><a class="headerlink" href="#bulk-create" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.bulk_create">
<code class="descname">bulk_create</code>(<em>objs</em>, <em>batch_size=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.bulk_create" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>This method inserts the provided list of objects into the database in an
efficient manner (generally only 1 query, no matter how many objects there
are):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">bulk_create</span><span class="p">([</span>
<span class="gp">... </span>    <span class="n">Entry</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s1">&#39;This is a test&#39;</span><span class="p">),</span>
<span class="gp">... </span>    <span class="n">Entry</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s1">&#39;This is only a test&#39;</span><span class="p">),</span>
<span class="gp">... </span><span class="p">])</span>
</pre></div>
</div>
<p>This has a number of caveats though:</p>
<ul class="simple">
<li>The model’s <code class="docutils literal notranslate"><span class="pre">save()</span></code> method will not be called, and the <code class="docutils literal notranslate"><span class="pre">pre_save</span></code> and
<code class="docutils literal notranslate"><span class="pre">post_save</span></code> signals will not be sent.</li>
<li>It does not work with child models in a multi-table inheritance scenario.</li>
<li>If the model’s primary key is an <a class="reference internal" href="fields.html#django.db.models.AutoField" title="django.db.models.AutoField"><code class="xref py py-class docutils literal notranslate"><span class="pre">AutoField</span></code></a> it
does not retrieve and set the primary key attribute, as <code class="docutils literal notranslate"><span class="pre">save()</span></code> does,
unless the database backend supports it (currently PostgreSQL).</li>
<li>It does not work with many-to-many relationships.</li>
</ul>
<div class="versionchanged">
<span class="title">Changed in Django 1.10:</span> <p>Support for setting primary keys on objects created using <code class="docutils literal notranslate"><span class="pre">bulk_create()</span></code>
when using PostgreSQL was added.</p>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">batch_size</span></code> parameter controls how many objects are created in single
query. The default is to create all objects in one batch, except for SQLite
where the default is such that at most 999 variables per query are used.</p>
</div>
<div class="section" id="s-count">
<span id="count"></span><h4><code class="docutils literal notranslate"><span class="pre">count()</span></code><a class="headerlink" href="#count" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.count">
<code class="descname">count</code>()<a class="headerlink" href="#django.db.models.query.QuerySet.count" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns an integer representing the number of objects in the database matching
the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>. The <code class="docutils literal notranslate"><span class="pre">count()</span></code> method never raises exceptions.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Returns the total number of entries in the database.</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>

<span class="c1"># Returns the number of entries whose headline contains &#39;Lennon&#39;</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
</pre></div>
</div>
<p>A <code class="docutils literal notranslate"><span class="pre">count()</span></code> call performs a <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">COUNT(*)</span></code> behind the scenes, so you
should always use <code class="docutils literal notranslate"><span class="pre">count()</span></code> rather than loading all of the record into Python
objects and calling <code class="docutils literal notranslate"><span class="pre">len()</span></code> on the result (unless you need to load the
objects into memory anyway, in which case <code class="docutils literal notranslate"><span class="pre">len()</span></code> will be faster).</p>
<p>Depending on which database you’re using (e.g. PostgreSQL vs. MySQL),
<code class="docutils literal notranslate"><span class="pre">count()</span></code> may return a long integer instead of a normal Python integer. This
is an underlying implementation quirk that shouldn’t pose any real-world
problems.</p>
<p>Note that if you want the number of items in a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> and are also
retrieving model instances from it (for example, by iterating over it), it’s
probably more efficient to use <code class="docutils literal notranslate"><span class="pre">len(queryset)</span></code> which won’t cause an extra
database query like <code class="docutils literal notranslate"><span class="pre">count()</span></code> would.</p>
</div>
<div class="section" id="s-in-bulk">
<span id="in-bulk"></span><h4><code class="docutils literal notranslate"><span class="pre">in_bulk()</span></code><a class="headerlink" href="#in-bulk" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.in_bulk">
<code class="descname">in_bulk</code>(<em>id_list=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.in_bulk" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Takes a list of primary-key values and returns a dictionary mapping each
primary-key value to an instance of the object with the given ID. If a list
isn’t provided, all objects in the queryset are returned.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">in_bulk</span><span class="p">([</span><span class="mi">1</span><span class="p">])</span>
<span class="go">{1: &lt;Blog: Beatles Blog&gt;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">in_bulk</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">])</span>
<span class="go">{1: &lt;Blog: Beatles Blog&gt;, 2: &lt;Blog: Cheddar Talk&gt;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">in_bulk</span><span class="p">([])</span>
<span class="go">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">in_bulk</span><span class="p">()</span>
<span class="go">{1: &lt;Blog: Beatles Blog&gt;, 2: &lt;Blog: Cheddar Talk&gt;, 3: &lt;Blog: Django Weblog&gt;}</span>
</pre></div>
</div>
<p>If you pass <code class="docutils literal notranslate"><span class="pre">in_bulk()</span></code> an empty list, you’ll get an empty dictionary.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.10:</span> <p>In older versions, <code class="docutils literal notranslate"><span class="pre">id_list</span></code> was a required argument.</p>
</div>
</div>
<div class="section" id="s-iterator">
<span id="iterator"></span><h4><code class="docutils literal notranslate"><span class="pre">iterator()</span></code><a class="headerlink" href="#iterator" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.iterator">
<code class="descname">iterator</code>()<a class="headerlink" href="#django.db.models.query.QuerySet.iterator" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Evaluates the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> (by performing the query) and returns an iterator
(see <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0234"><strong>PEP 234</strong></a>) over the results. A <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> typically caches its results
internally so that repeated evaluations do not result in additional queries. In
contrast, <code class="docutils literal notranslate"><span class="pre">iterator()</span></code> will read results directly, without doing any caching
at the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> level (internally, the default iterator calls <code class="docutils literal notranslate"><span class="pre">iterator()</span></code>
and caches the return value). For a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> which returns a large number of
objects that you only need to access once, this can result in better
performance and a significant reduction in memory.</p>
<p>Note that using <code class="docutils literal notranslate"><span class="pre">iterator()</span></code> on a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> which has already been
evaluated will force it to evaluate again, repeating the query.</p>
<p>Also, use of <code class="docutils literal notranslate"><span class="pre">iterator()</span></code> causes previous <code class="docutils literal notranslate"><span class="pre">prefetch_related()</span></code> calls to be
ignored since these two optimizations do not make sense together.</p>
<p>Depending on the database backend, query results will either be loaded all at
once or streamed from the database using server-side cursors.</p>
<div class="section" id="s-with-server-side-cursors">
<span id="with-server-side-cursors"></span><h5>With server-side cursors<a class="headerlink" href="#with-server-side-cursors" title="Permalink to this headline">¶</a></h5>
<p>Oracle and <a class="reference internal" href="../databases.html#postgresql-server-side-cursors"><span class="std std-ref">PostgreSQL</span></a> use server-side
cursors to stream results from the database without loading the entire result
set into memory.</p>
<p>The Oracle database driver always uses server-side cursors.</p>
<p>On PostgreSQL, server-side cursors will only be used when the
<a class="reference internal" href="../settings.html#std:setting-DATABASE-DISABLE_SERVER_SIDE_CURSORS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DISABLE_SERVER_SIDE_CURSORS</span></code></a>
setting is <code class="docutils literal notranslate"><span class="pre">False</span></code>. Read <a class="reference internal" href="../databases.html#transaction-pooling-server-side-cursors"><span class="std std-ref">Transaction pooling and server-side cursors</span></a> if
you’re using a connection pooler configured in transaction pooling mode. When
server-side cursors are disabled, the behavior is the same as databases that
don’t support server-side cursors.</p>
</div>
<div class="section" id="s-without-server-side-cursors">
<span id="without-server-side-cursors"></span><h5>Without server-side cursors<a class="headerlink" href="#without-server-side-cursors" title="Permalink to this headline">¶</a></h5>
<p>MySQL and SQLite don’t support streaming results, hence the Python database
drivers load the entire result set into memory. The result set is then
transformed into Python row objects by the database adapter using the
<code class="docutils literal notranslate"><span class="pre">fetchmany()</span></code> method defined in <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.11:</span> <p>PostgreSQL support for server-side cursors was added.</p>
</div>
</div>
</div>
<div class="section" id="s-latest">
<span id="latest"></span><h4><code class="docutils literal notranslate"><span class="pre">latest()</span></code><a class="headerlink" href="#latest" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.latest">
<code class="descname">latest</code>(<em>field_name=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.latest" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns the latest object in the table, by date, using the <code class="docutils literal notranslate"><span class="pre">field_name</span></code>
provided as the date field.</p>
<p>This example returns the latest <code class="docutils literal notranslate"><span class="pre">Entry</span></code> in the table, according to the
<code class="docutils literal notranslate"><span class="pre">pub_date</span></code> field:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">latest</span><span class="p">(</span><span class="s1">&#39;pub_date&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If your model’s <a class="reference internal" href="../../topics/db/models.html#meta-options"><span class="std std-ref">Meta</span></a> specifies
<a class="reference internal" href="options.html#django.db.models.Options.get_latest_by" title="django.db.models.Options.get_latest_by"><code class="xref py py-attr docutils literal notranslate"><span class="pre">get_latest_by</span></code></a>, you can leave off the
<code class="docutils literal notranslate"><span class="pre">field_name</span></code> argument to <code class="docutils literal notranslate"><span class="pre">earliest()</span></code> or <code class="docutils literal notranslate"><span class="pre">latest()</span></code>. Django will use the
field specified in <a class="reference internal" href="options.html#django.db.models.Options.get_latest_by" title="django.db.models.Options.get_latest_by"><code class="xref py py-attr docutils literal notranslate"><span class="pre">get_latest_by</span></code></a> by default.</p>
<p>Like <a class="reference internal" href="#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">earliest()</span></code> and <code class="docutils literal notranslate"><span class="pre">latest()</span></code> raise
<a class="reference internal" href="instances.html#django.db.models.Model.DoesNotExist" title="django.db.models.Model.DoesNotExist"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DoesNotExist</span></code></a> if there is no object with the
given parameters.</p>
<p>Note that <code class="docutils literal notranslate"><span class="pre">earliest()</span></code> and <code class="docutils literal notranslate"><span class="pre">latest()</span></code> exist purely for convenience and
readability.</p>
<div class="admonition-earliest-and-latest-may-return-instances-with-null-dates admonition">
<p class="first admonition-title"><code class="docutils literal notranslate"><span class="pre">earliest()</span></code> and <code class="docutils literal notranslate"><span class="pre">latest()</span></code> may return instances with null dates.</p>
<p>Since ordering is delegated to the database, results on fields that allow
null values may be ordered differently if you use different databases. For
example, PostgreSQL and MySQL sort null values as if they are higher than
non-null values, while SQLite does the opposite.</p>
<p>You may want to filter out null values:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__isnull</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span><span class="o">.</span><span class="n">latest</span><span class="p">(</span><span class="s1">&#39;pub_date&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-earliest">
<span id="earliest"></span><h4><code class="docutils literal notranslate"><span class="pre">earliest()</span></code><a class="headerlink" href="#earliest" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.earliest">
<code class="descname">earliest</code>(<em>field_name=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.earliest" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Works otherwise like <a class="reference internal" href="#django.db.models.query.QuerySet.latest" title="django.db.models.query.QuerySet.latest"><code class="xref py py-meth docutils literal notranslate"><span class="pre">latest()</span></code></a> except
the direction is changed.</p>
</div>
<div class="section" id="s-first">
<span id="first"></span><h4><code class="docutils literal notranslate"><span class="pre">first()</span></code><a class="headerlink" href="#first" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.first">
<code class="descname">first</code>()<a class="headerlink" href="#django.db.models.query.QuerySet.first" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns the first object matched by the queryset, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if there
is no matching object. If the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> has no ordering defined, then the
queryset is automatically ordered by the primary key.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span> <span class="o">=</span> <span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;title&#39;</span><span class="p">,</span> <span class="s1">&#39;pub_date&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
</pre></div>
</div>
<p>Note that <code class="docutils literal notranslate"><span class="pre">first()</span></code> is a convenience method, the following code sample is
equivalent to the above example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;title&#39;</span><span class="p">,</span> <span class="s1">&#39;pub_date&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
<span class="k">except</span> <span class="ne">IndexError</span><span class="p">:</span>
    <span class="n">p</span> <span class="o">=</span> <span class="kc">None</span>
</pre></div>
</div>
</div>
<div class="section" id="s-last">
<span id="last"></span><h4><code class="docutils literal notranslate"><span class="pre">last()</span></code><a class="headerlink" href="#last" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.last">
<code class="descname">last</code>()<a class="headerlink" href="#django.db.models.query.QuerySet.last" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Works like  <a class="reference internal" href="#django.db.models.query.QuerySet.first" title="django.db.models.query.QuerySet.first"><code class="xref py py-meth docutils literal notranslate"><span class="pre">first()</span></code></a>, but returns the last object in the queryset.</p>
</div>
<div class="section" id="s-aggregate">
<span id="aggregate"></span><h4><code class="docutils literal notranslate"><span class="pre">aggregate()</span></code><a class="headerlink" href="#aggregate" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.aggregate">
<code class="descname">aggregate</code>(<em>*args</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.aggregate" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a dictionary of aggregate values (averages, sums, etc.) calculated over
the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>. Each argument to <code class="docutils literal notranslate"><span class="pre">aggregate()</span></code> specifies a value that will
be included in the dictionary that is returned.</p>
<p>The aggregation functions that are provided by Django are described in
<a class="reference internal" href="#id5">Aggregation Functions</a> below. Since aggregates are also <a class="reference internal" href="expressions.html"><span class="doc">query
expressions</span></a>, you may combine aggregates with other
aggregates or values to create complex aggregates.</p>
<p>Aggregates specified using keyword arguments will use the keyword as the name
for the annotation. Anonymous arguments will have a name generated for them
based upon the name of the aggregate function and the model field that is being
aggregated. Complex aggregates cannot use anonymous arguments and must specify
a keyword argument as an alias.</p>
<p>For example, when you are working with blog entries, you may want to know the
number of authors that have contributed blog entries:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="k">import</span> <span class="n">Count</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">aggregate</span><span class="p">(</span><span class="n">Count</span><span class="p">(</span><span class="s1">&#39;entry&#39;</span><span class="p">))</span>
<span class="go">{&#39;entry__count&#39;: 16}</span>
</pre></div>
</div>
<p>By using a keyword argument to specify the aggregate function, you can
control the name of the aggregation value that is returned:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">aggregate</span><span class="p">(</span><span class="n">number_of_entries</span><span class="o">=</span><span class="n">Count</span><span class="p">(</span><span class="s1">&#39;entry&#39;</span><span class="p">))</span>
<span class="go">{&#39;number_of_entries&#39;: 16}</span>
</pre></div>
</div>
<p>For an in-depth discussion of aggregation, see <a class="reference internal" href="../../topics/db/aggregation.html"><span class="doc">the topic guide on
Aggregation</span></a>.</p>
</div>
<div class="section" id="s-exists">
<span id="exists"></span><h4><code class="docutils literal notranslate"><span class="pre">exists()</span></code><a class="headerlink" href="#exists" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.exists">
<code class="descname">exists</code>()<a class="headerlink" href="#django.db.models.query.QuerySet.exists" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> contains any results, and <code class="docutils literal notranslate"><span class="pre">False</span></code>
if not. This tries to perform the query in the simplest and fastest way
possible, but it <em>does</em> execute nearly the same query as a normal
<a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> query.</p>
<p><a class="reference internal" href="#django.db.models.query.QuerySet.exists" title="django.db.models.query.QuerySet.exists"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exists()</span></code></a> is useful for searches relating to both
object membership in a <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> and to the existence of any objects in
a <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>, particularly in the context of a large <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>.</p>
<p>The most efficient method of finding whether a model with a unique field
(e.g. <code class="docutils literal notranslate"><span class="pre">primary_key</span></code>) is a member of a <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">entry</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">123</span><span class="p">)</span>
<span class="k">if</span> <span class="n">some_queryset</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">entry</span><span class="o">.</span><span class="n">pk</span><span class="p">)</span><span class="o">.</span><span class="n">exists</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Entry contained in queryset&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Which will be faster than the following which requires evaluating and iterating
through the entire queryset:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">entry</span> <span class="ow">in</span> <span class="n">some_queryset</span><span class="p">:</span>
   <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Entry contained in QuerySet&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>And to find whether a queryset contains any items:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">some_queryset</span><span class="o">.</span><span class="n">exists</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;There is at least one object in some_queryset&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Which will be faster than:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">some_queryset</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;There is at least one object in some_queryset&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>… but not by a large degree (hence needing a large queryset for efficiency
gains).</p>
<p>Additionally, if a <code class="docutils literal notranslate"><span class="pre">some_queryset</span></code> has not yet been evaluated, but you know
that it will be at some point, then using <code class="docutils literal notranslate"><span class="pre">some_queryset.exists()</span></code> will do
more overall work (one query for the existence check plus an extra one to later
retrieve the results) than simply using <code class="docutils literal notranslate"><span class="pre">bool(some_queryset)</span></code>, which
retrieves the results and then checks if any were returned.</p>
</div>
<div class="section" id="s-update">
<span id="update"></span><h4><code class="docutils literal notranslate"><span class="pre">update()</span></code><a class="headerlink" href="#update" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.update">
<code class="descname">update</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.update" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Performs an SQL update query for the specified fields, and returns
the number of rows matched (which may not be equal to the number of rows
updated if some rows already have the new value).</p>
<p>For example, to turn comments off for all blog entries published in 2010,
you could do this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2010</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
</pre></div>
</div>
<p>(This assumes your <code class="docutils literal notranslate"><span class="pre">Entry</span></code> model has fields <code class="docutils literal notranslate"><span class="pre">pub_date</span></code> and <code class="docutils literal notranslate"><span class="pre">comments_on</span></code>.)</p>
<p>You can update multiple fields — there’s no limit on how many. For example,
here we update the <code class="docutils literal notranslate"><span class="pre">comments_on</span></code> and <code class="docutils literal notranslate"><span class="pre">headline</span></code> fields:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2010</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">headline</span><span class="o">=</span><span class="s1">&#39;This is old&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">update()</span></code> method is applied instantly, and the only restriction on the
<a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> that is updated is that it can only update columns in the
model’s main table, not on related models. You can’t do this, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">blog__name</span><span class="o">=</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span> <span class="c1"># Won&#39;t work!</span>
</pre></div>
</div>
<p>Filtering based on related fields is still possible, though:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>You cannot call <code class="docutils literal notranslate"><span class="pre">update()</span></code> on a <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> that has had a slice taken
or can otherwise no longer be filtered.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">update()</span></code> method returns the number of affected rows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">64</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">1</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">slug</span><span class="o">=</span><span class="s1">&#39;nonexistent-slug&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">0</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2010</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="go">132</span>
</pre></div>
</div>
<p>If you’re just updating a record and don’t need to do anything with the model
object, the most efficient approach is to call <code class="docutils literal notranslate"><span class="pre">update()</span></code>, rather than
loading the model object into memory. For example, instead of doing this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
<span class="n">e</span><span class="o">.</span><span class="n">comments_on</span> <span class="o">=</span> <span class="kc">False</span>
<span class="n">e</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>…do this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
</pre></div>
</div>
<p>Using <code class="docutils literal notranslate"><span class="pre">update()</span></code> also prevents a race condition wherein something might
change in your database in the short period of time between loading the object
and calling <code class="docutils literal notranslate"><span class="pre">save()</span></code>.</p>
<p>Finally, realize that <code class="docutils literal notranslate"><span class="pre">update()</span></code> does an update at the SQL level and, thus,
does not call any <code class="docutils literal notranslate"><span class="pre">save()</span></code> methods on your models, nor does it emit the
<a class="reference internal" href="../signals.html#django.db.models.signals.pre_save" title="django.db.models.signals.pre_save"><code class="xref py py-attr docutils literal notranslate"><span class="pre">pre_save</span></code></a> or
<a class="reference internal" href="../signals.html#django.db.models.signals.post_save" title="django.db.models.signals.post_save"><code class="xref py py-attr docutils literal notranslate"><span class="pre">post_save</span></code></a> signals (which are a consequence of
calling <a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Model.save()</span></code></a>). If you want to
update a bunch of records for a model that has a custom
<a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> method, loop over them and call
<a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a>, like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2010</span><span class="p">):</span>
    <span class="n">e</span><span class="o">.</span><span class="n">comments_on</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="n">e</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="s-delete">
<span id="delete"></span><h4><code class="docutils literal notranslate"><span class="pre">delete()</span></code><a class="headerlink" href="#delete" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.delete">
<code class="descname">delete</code>()<a class="headerlink" href="#django.db.models.query.QuerySet.delete" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Performs an SQL delete query on all rows in the <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> and
returns the number of objects deleted and a dictionary with the number of
deletions per object type.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">delete()</span></code> is applied instantly. You cannot call <code class="docutils literal notranslate"><span class="pre">delete()</span></code> on a
<a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> that has had a slice taken or can otherwise no longer be
filtered.</p>
<p>For example, to delete all the entries in a particular blog:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

<span class="go"># Delete all the entries belonging to this Blog.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog</span><span class="o">=</span><span class="n">b</span><span class="p">)</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="go">(4, {&#39;weblog.Entry&#39;: 2, &#39;weblog.Entry_authors&#39;: 2})</span>
</pre></div>
</div>
<p>By default, Django’s <a class="reference internal" href="fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> emulates the SQL
constraint <code class="docutils literal notranslate"><span class="pre">ON</span> <span class="pre">DELETE</span> <span class="pre">CASCADE</span></code> — in other words, any objects with foreign
keys pointing at the objects to be deleted will be deleted along with them.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">blogs</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>

<span class="go"># This will delete all Blogs and all of their Entry objects.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">blogs</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="go">(5, {&#39;weblog.Blog&#39;: 1, &#39;weblog.Entry&#39;: 2, &#39;weblog.Entry_authors&#39;: 2})</span>
</pre></div>
</div>
<p>This cascade behavior is customizable via the
<a class="reference internal" href="fields.html#django.db.models.ForeignKey.on_delete" title="django.db.models.ForeignKey.on_delete"><code class="xref py py-attr docutils literal notranslate"><span class="pre">on_delete</span></code></a> argument to the
<a class="reference internal" href="fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">delete()</span></code> method does a bulk delete and does not call any <code class="docutils literal notranslate"><span class="pre">delete()</span></code>
methods on your models. It does, however, emit the
<a class="reference internal" href="../signals.html#django.db.models.signals.pre_delete" title="django.db.models.signals.pre_delete"><code class="xref py py-data docutils literal notranslate"><span class="pre">pre_delete</span></code></a> and
<a class="reference internal" href="../signals.html#django.db.models.signals.post_delete" title="django.db.models.signals.post_delete"><code class="xref py py-data docutils literal notranslate"><span class="pre">post_delete</span></code></a> signals for all deleted objects
(including cascaded deletions).</p>
<p>Django needs to fetch objects into memory to send signals and handle cascades.
However, if there are no cascades and no signals, then Django may take a
fast-path and delete objects without fetching into memory. For large
deletes this can result in significantly reduced memory usage. The amount of
executed queries can be reduced, too.</p>
<p>ForeignKeys which are set to <a class="reference internal" href="fields.html#django.db.models.ForeignKey.on_delete" title="django.db.models.ForeignKey.on_delete"><code class="xref py py-attr docutils literal notranslate"><span class="pre">on_delete</span></code></a>
<code class="docutils literal notranslate"><span class="pre">DO_NOTHING</span></code> do not prevent taking the fast-path in deletion.</p>
<p>Note that the queries generated in object deletion is an implementation
detail subject to change.</p>
</div>
<div class="section" id="s-as-manager">
<span id="as-manager"></span><h4><code class="docutils literal notranslate"><span class="pre">as_manager()</span></code><a class="headerlink" href="#as-manager" title="Permalink to this headline">¶</a></h4>
<dl class="classmethod">
<dt id="django.db.models.query.QuerySet.as_manager">
<em class="property">classmethod </em><code class="descname">as_manager</code>()<a class="headerlink" href="#django.db.models.query.QuerySet.as_manager" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Class method that returns an instance of <a class="reference internal" href="../../topics/db/managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a>
with a copy of the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>’s methods. See
<a class="reference internal" href="../../topics/db/managers.html#create-manager-with-queryset-methods"><span class="std std-ref">Creating a manager with QuerySet methods</span></a> for more details.</p>
</div>
</div>
<div class="section" id="s-field-lookups">
<span id="s-id4"></span><span id="field-lookups"></span><span id="id4"></span><h3><code class="docutils literal notranslate"><span class="pre">Field</span></code> lookups<a class="headerlink" href="#field-lookups" title="Permalink to this headline">¶</a></h3>
<p>Field lookups are how you specify the meat of an SQL <code class="docutils literal notranslate"><span class="pre">WHERE</span></code> clause. They’re
specified as keyword arguments to the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> methods <a class="reference internal" href="#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a>,
<a class="reference internal" href="#django.db.models.query.QuerySet.exclude" title="django.db.models.query.QuerySet.exclude"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exclude()</span></code></a> and <a class="reference internal" href="#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>.</p>
<p>For an introduction, see <a class="reference internal" href="../../topics/db/queries.html#field-lookups-intro"><span class="std std-ref">models and database queries documentation</span></a>.</p>
<p>Django’s built-in lookups are listed below. It is also possible to write
<a class="reference internal" href="../../howto/custom-lookups.html"><span class="doc">custom lookups</span></a> for model fields.</p>
<p>As a convenience when no lookup type is provided (like in
<code class="docutils literal notranslate"><span class="pre">Entry.objects.get(id=14)</span></code>) the lookup type is assumed to be <a class="reference internal" href="#std:fieldlookup-exact"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">exact</span></code></a>.</p>
<div class="section" id="s-exact">
<span id="s-std:fieldlookup-exact"></span><span id="exact"></span><span id="std:fieldlookup-exact"></span><h4><code class="docutils literal notranslate"><span class="pre">exact</span></code><a class="headerlink" href="#exact" title="Permalink to this headline">¶</a></h4>
<p>Exact match. If the value provided for comparison is <code class="docutils literal notranslate"><span class="pre">None</span></code>, it will be
interpreted as an SQL <code class="docutils literal notranslate"><span class="pre">NULL</span></code> (see <a class="reference internal" href="#std:fieldlookup-isnull"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">isnull</span></code></a> for more details).</p>
<p>Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">id__exact</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">id__exact</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalents:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="nb">id</span> <span class="o">=</span> <span class="mi">14</span><span class="p">;</span>
<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="nb">id</span> <span class="n">IS</span> <span class="n">NULL</span><span class="p">;</span>
</pre></div>
</div>
<div class="admonition-mysql-comparisons admonition">
<p class="first admonition-title">MySQL comparisons</p>
<p class="last">In MySQL, a database table’s “collation” setting determines whether
<code class="docutils literal notranslate"><span class="pre">exact</span></code> comparisons are case-sensitive. This is a database setting, <em>not</em>
a Django setting. It’s possible to configure your MySQL tables to use
case-sensitive comparisons, but some trade-offs are involved. For more
information about this, see the <a class="reference internal" href="../databases.html#mysql-collation"><span class="std std-ref">collation section</span></a>
in the <a class="reference internal" href="../databases.html"><span class="doc">databases</span></a> documentation.</p>
</div>
</div>
<div class="section" id="s-iexact">
<span id="s-std:fieldlookup-iexact"></span><span id="iexact"></span><span id="std:fieldlookup-iexact"></span><h4><code class="docutils literal notranslate"><span class="pre">iexact</span></code><a class="headerlink" href="#iexact" title="Permalink to this headline">¶</a></h4>
<p>Case-insensitive exact match. If the value provided for comparison is <code class="docutils literal notranslate"><span class="pre">None</span></code>,
it will be interpreted as an SQL <code class="docutils literal notranslate"><span class="pre">NULL</span></code> (see <a class="reference internal" href="#std:fieldlookup-isnull"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">isnull</span></code></a> for more
details).</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name__iexact</span><span class="o">=</span><span class="s1">&#39;beatles blog&#39;</span><span class="p">)</span>
<span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name__iexact</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalents:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">name</span> <span class="n">ILIKE</span> <span class="s1">&#39;beatles blog&#39;</span><span class="p">;</span>
<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">name</span> <span class="n">IS</span> <span class="n">NULL</span><span class="p">;</span>
</pre></div>
</div>
<p>Note the first query will match <code class="docutils literal notranslate"><span class="pre">'Beatles</span> <span class="pre">Blog'</span></code>, <code class="docutils literal notranslate"><span class="pre">'beatles</span> <span class="pre">blog'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'BeAtLes</span> <span class="pre">BLoG'</span></code>, etc.</p>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">When using the SQLite backend and Unicode (non-ASCII) strings, bear in
mind the <a class="reference internal" href="../databases.html#sqlite-string-matching"><span class="std std-ref">database note</span></a> about string
comparisons. SQLite does not do case-insensitive matching for Unicode
strings.</p>
</div>
</div>
<div class="section" id="s-contains">
<span id="s-std:fieldlookup-contains"></span><span id="contains"></span><span id="std:fieldlookup-contains"></span><h4><code class="docutils literal notranslate"><span class="pre">contains</span></code><a class="headerlink" href="#contains" title="Permalink to this headline">¶</a></h4>
<p>Case-sensitive containment test.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">headline</span> <span class="n">LIKE</span> <span class="s1">&#39;</span><span class="si">%Le</span><span class="s1">nnon%&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>Note this will match the headline <code class="docutils literal notranslate"><span class="pre">'Lennon</span> <span class="pre">honored</span> <span class="pre">today'</span></code> but not <code class="docutils literal notranslate"><span class="pre">'lennon</span>
<span class="pre">honored</span> <span class="pre">today'</span></code>.</p>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">SQLite doesn’t support case-sensitive <code class="docutils literal notranslate"><span class="pre">LIKE</span></code> statements; <code class="docutils literal notranslate"><span class="pre">contains</span></code>
acts like <code class="docutils literal notranslate"><span class="pre">icontains</span></code> for SQLite. See the <a class="reference internal" href="../databases.html#sqlite-string-matching"><span class="std std-ref">database note</span></a> for more information.</p>
</div>
</div>
<div class="section" id="s-icontains">
<span id="s-std:fieldlookup-icontains"></span><span id="icontains"></span><span id="std:fieldlookup-icontains"></span><h4><code class="docutils literal notranslate"><span class="pre">icontains</span></code><a class="headerlink" href="#icontains" title="Permalink to this headline">¶</a></h4>
<p>Case-insensitive containment test.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">headline__icontains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">headline</span> <span class="n">ILIKE</span> <span class="s1">&#39;</span><span class="si">%Le</span><span class="s1">nnon%&#39;</span><span class="p">;</span>
</pre></div>
</div>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">When using the SQLite backend and Unicode (non-ASCII) strings, bear in
mind the <a class="reference internal" href="../databases.html#sqlite-string-matching"><span class="std std-ref">database note</span></a> about string
comparisons.</p>
</div>
</div>
<div class="section" id="s-in">
<span id="s-std:fieldlookup-in"></span><span id="in"></span><span id="std:fieldlookup-in"></span><h4><code class="docutils literal notranslate"><span class="pre">in</span></code><a class="headerlink" href="#in" title="Permalink to this headline">¶</a></h4>
<p>In a given list.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">id__in</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">])</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="nb">id</span> <span class="n">IN</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">);</span>
</pre></div>
</div>
<p>You can also use a queryset to dynamically evaluate the list of values
instead of providing a list of literal values:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">inner_qs</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name__contains</span><span class="o">=</span><span class="s1">&#39;Cheddar&#39;</span><span class="p">)</span>
<span class="n">entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__in</span><span class="o">=</span><span class="n">inner_qs</span><span class="p">)</span>
</pre></div>
</div>
<p>This queryset will be evaluated as subselect statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">blog</span><span class="o">.</span><span class="n">id</span> <span class="n">IN</span> <span class="p">(</span><span class="n">SELECT</span> <span class="nb">id</span> <span class="n">FROM</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">NAME</span> <span class="n">LIKE</span> <span class="s1">&#39;%Cheddar%&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you pass in a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> resulting from <code class="docutils literal notranslate"><span class="pre">values()</span></code> or <code class="docutils literal notranslate"><span class="pre">values_list()</span></code>
as the value to an <code class="docutils literal notranslate"><span class="pre">__in</span></code> lookup, you need to ensure you are only extracting
one field in the result. For example, this will work (filtering on the blog
names):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">inner_qs</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name__contains</span><span class="o">=</span><span class="s1">&#39;Ch&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">)</span>
<span class="n">entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__name__in</span><span class="o">=</span><span class="n">inner_qs</span><span class="p">)</span>
</pre></div>
</div>
<p>This example will raise an exception, since the inner query is trying to
extract two field values, where only one is expected:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Bad code! Will raise a TypeError.</span>
<span class="n">inner_qs</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name__contains</span><span class="o">=</span><span class="s1">&#39;Ch&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;id&#39;</span><span class="p">)</span>
<span class="n">entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__name__in</span><span class="o">=</span><span class="n">inner_qs</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition-performance-considerations admonition" id="nested-queries-performance">
<p class="first admonition-title">Performance considerations</p>
<p>Be cautious about using nested queries and understand your database
server’s performance characteristics (if in doubt, benchmark!). Some
database backends, most notably MySQL, don’t optimize nested queries very
well. It is more efficient, in those cases, to extract a list of values
and then pass that into the second query. That is, execute two queries
instead of one:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">values</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
        <span class="n">name__contains</span><span class="o">=</span><span class="s1">&#39;Cheddar&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s1">&#39;pk&#39;</span><span class="p">,</span> <span class="n">flat</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="n">entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__in</span><span class="o">=</span><span class="nb">list</span><span class="p">(</span><span class="n">values</span><span class="p">))</span>
</pre></div>
</div>
<p class="last">Note the <code class="docutils literal notranslate"><span class="pre">list()</span></code> call around the Blog <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> to force execution of
the first query. Without it, a nested query would be executed, because
<a class="reference internal" href="../../topics/db/queries.html#querysets-are-lazy"><span class="std std-ref">QuerySets are lazy</span></a>.</p>
</div>
</div>
<div class="section" id="s-gt">
<span id="s-std:fieldlookup-gt"></span><span id="gt"></span><span id="std:fieldlookup-gt"></span><h4><code class="docutils literal notranslate"><span class="pre">gt</span></code><a class="headerlink" href="#gt" title="Permalink to this headline">¶</a></h4>
<p>Greater than.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">id__gt</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="nb">id</span> <span class="o">&gt;</span> <span class="mi">4</span><span class="p">;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-gte">
<span id="s-std:fieldlookup-gte"></span><span id="gte"></span><span id="std:fieldlookup-gte"></span><h4><code class="docutils literal notranslate"><span class="pre">gte</span></code><a class="headerlink" href="#gte" title="Permalink to this headline">¶</a></h4>
<p>Greater than or equal to.</p>
</div>
<div class="section" id="s-lt">
<span id="s-std:fieldlookup-lt"></span><span id="lt"></span><span id="std:fieldlookup-lt"></span><h4><code class="docutils literal notranslate"><span class="pre">lt</span></code><a class="headerlink" href="#lt" title="Permalink to this headline">¶</a></h4>
<p>Less than.</p>
</div>
<div class="section" id="s-lte">
<span id="s-std:fieldlookup-lte"></span><span id="lte"></span><span id="std:fieldlookup-lte"></span><h4><code class="docutils literal notranslate"><span class="pre">lte</span></code><a class="headerlink" href="#lte" title="Permalink to this headline">¶</a></h4>
<p>Less than or equal to.</p>
</div>
<div class="section" id="s-startswith">
<span id="s-std:fieldlookup-startswith"></span><span id="startswith"></span><span id="std:fieldlookup-startswith"></span><h4><code class="docutils literal notranslate"><span class="pre">startswith</span></code><a class="headerlink" href="#startswith" title="Permalink to this headline">¶</a></h4>
<p>Case-sensitive starts-with.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__startswith</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">headline</span> <span class="n">LIKE</span> <span class="s1">&#39;Lennon%&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>SQLite doesn’t support case-sensitive <code class="docutils literal notranslate"><span class="pre">LIKE</span></code> statements; <code class="docutils literal notranslate"><span class="pre">startswith</span></code> acts
like <code class="docutils literal notranslate"><span class="pre">istartswith</span></code> for SQLite.</p>
</div>
<div class="section" id="s-istartswith">
<span id="s-std:fieldlookup-istartswith"></span><span id="istartswith"></span><span id="std:fieldlookup-istartswith"></span><h4><code class="docutils literal notranslate"><span class="pre">istartswith</span></code><a class="headerlink" href="#istartswith" title="Permalink to this headline">¶</a></h4>
<p>Case-insensitive starts-with.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__istartswith</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">headline</span> <span class="n">ILIKE</span> <span class="s1">&#39;Lennon%&#39;</span><span class="p">;</span>
</pre></div>
</div>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">When using the SQLite backend and Unicode (non-ASCII) strings, bear in
mind the <a class="reference internal" href="../databases.html#sqlite-string-matching"><span class="std std-ref">database note</span></a> about string
comparisons.</p>
</div>
</div>
<div class="section" id="s-endswith">
<span id="s-std:fieldlookup-endswith"></span><span id="endswith"></span><span id="std:fieldlookup-endswith"></span><h4><code class="docutils literal notranslate"><span class="pre">endswith</span></code><a class="headerlink" href="#endswith" title="Permalink to this headline">¶</a></h4>
<p>Case-sensitive ends-with.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__endswith</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">headline</span> <span class="n">LIKE</span> <span class="s1">&#39;</span><span class="si">%Le</span><span class="s1">nnon&#39;</span><span class="p">;</span>
</pre></div>
</div>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">SQLite doesn’t support case-sensitive <code class="docutils literal notranslate"><span class="pre">LIKE</span></code> statements; <code class="docutils literal notranslate"><span class="pre">endswith</span></code>
acts like <code class="docutils literal notranslate"><span class="pre">iendswith</span></code> for SQLite. Refer to the <a class="reference internal" href="../databases.html#sqlite-string-matching"><span class="std std-ref">database note</span></a> documentation for more.</p>
</div>
</div>
<div class="section" id="s-iendswith">
<span id="s-std:fieldlookup-iendswith"></span><span id="iendswith"></span><span id="std:fieldlookup-iendswith"></span><h4><code class="docutils literal notranslate"><span class="pre">iendswith</span></code><a class="headerlink" href="#iendswith" title="Permalink to this headline">¶</a></h4>
<p>Case-insensitive ends-with.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__iendswith</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">headline</span> <span class="n">ILIKE</span> <span class="s1">&#39;</span><span class="si">%Le</span><span class="s1">nnon&#39;</span>
</pre></div>
</div>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">When using the SQLite backend and Unicode (non-ASCII) strings, bear in
mind the <a class="reference internal" href="../databases.html#sqlite-string-matching"><span class="std std-ref">database note</span></a> about string
comparisons.</p>
</div>
</div>
<div class="section" id="s-range">
<span id="s-std:fieldlookup-range"></span><span id="range"></span><span id="std:fieldlookup-range"></span><h4><code class="docutils literal notranslate"><span class="pre">range</span></code><a class="headerlink" href="#range" title="Permalink to this headline">¶</a></h4>
<p>Range test (inclusive).</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">datetime</span>
<span class="n">start_date</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">end_date</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">31</span><span class="p">)</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__range</span><span class="o">=</span><span class="p">(</span><span class="n">start_date</span><span class="p">,</span> <span class="n">end_date</span><span class="p">))</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">pub_date</span> <span class="n">BETWEEN</span> <span class="s1">&#39;2005-01-01&#39;</span> <span class="ow">and</span> <span class="s1">&#39;2005-03-31&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>You can use <code class="docutils literal notranslate"><span class="pre">range</span></code> anywhere you can use <code class="docutils literal notranslate"><span class="pre">BETWEEN</span></code> in SQL — for dates,
numbers and even characters.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>Filtering a <code class="docutils literal notranslate"><span class="pre">DateTimeField</span></code> with dates won’t include items on the last
day, because the bounds are interpreted as “0am on the given date”. If
<code class="docutils literal notranslate"><span class="pre">pub_date</span></code> was a <code class="docutils literal notranslate"><span class="pre">DateTimeField</span></code>, the above expression would be turned
into this SQL:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">pub_date</span> <span class="n">BETWEEN</span> <span class="s1">&#39;2005-01-01 00:00:00&#39;</span> <span class="ow">and</span> <span class="s1">&#39;2005-03-31 00:00:00&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p class="last">Generally speaking, you can’t mix dates and datetimes.</p>
</div>
</div>
<div class="section" id="s-date">
<span id="s-std:fieldlookup-date"></span><span id="date"></span><span id="std:fieldlookup-date"></span><h4><code class="docutils literal notranslate"><span class="pre">date</span></code><a class="headerlink" href="#date" title="Permalink to this headline">¶</a></h4>
<p>For datetime fields, casts the value as date. Allows chaining additional field
lookups. Takes a date value.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__date</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">))</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__date__gt</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">))</span>
</pre></div>
</div>
<p>(No equivalent SQL code fragment is included for this lookup because
implementation of the relevant query varies among different database engines.)</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, fields are converted to the current time
zone before filtering.</p>
</div>
<div class="section" id="s-year">
<span id="s-std:fieldlookup-year"></span><span id="year"></span><span id="std:fieldlookup-year"></span><h4><code class="docutils literal notranslate"><span class="pre">year</span></code><a class="headerlink" href="#year" title="Permalink to this headline">¶</a></h4>
<p>For date and datetime fields, an exact year match. Allows chaining additional
field lookups. Takes an integer year.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2005</span><span class="p">)</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year__gte</span><span class="o">=</span><span class="mi">2005</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">pub_date</span> <span class="n">BETWEEN</span> <span class="s1">&#39;2005-01-01&#39;</span> <span class="n">AND</span> <span class="s1">&#39;2005-12-31&#39;</span><span class="p">;</span>
<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">pub_date</span> <span class="o">&gt;=</span> <span class="s1">&#39;2005-01-01&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, datetime fields are converted to the
current time zone before filtering.</p>
</div>
<div class="section" id="s-month">
<span id="s-std:fieldlookup-month"></span><span id="month"></span><span id="std:fieldlookup-month"></span><h4><code class="docutils literal notranslate"><span class="pre">month</span></code><a class="headerlink" href="#month" title="Permalink to this headline">¶</a></h4>
<p>For date and datetime fields, an exact month match. Allows chaining additional
field lookups. Takes an integer 1 (January) through 12 (December).</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__month</span><span class="o">=</span><span class="mi">12</span><span class="p">)</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__month__gte</span><span class="o">=</span><span class="mi">6</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;month&#39;</span> <span class="n">FROM</span> <span class="n">pub_date</span><span class="p">)</span> <span class="o">=</span> <span class="s1">&#39;12&#39;</span><span class="p">;</span>
<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;month&#39;</span> <span class="n">FROM</span> <span class="n">pub_date</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="s1">&#39;6&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, datetime fields are converted to the
current time zone before filtering. This requires <a class="reference internal" href="#database-time-zone-definitions"><span class="std std-ref">time zone definitions
in the database</span></a>.</p>
</div>
<div class="section" id="s-day">
<span id="s-std:fieldlookup-day"></span><span id="day"></span><span id="std:fieldlookup-day"></span><h4><code class="docutils literal notranslate"><span class="pre">day</span></code><a class="headerlink" href="#day" title="Permalink to this headline">¶</a></h4>
<p>For date and datetime fields, an exact day match. Allows chaining additional
field lookups. Takes an integer day.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__day</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__day__gte</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;day&#39;</span> <span class="n">FROM</span> <span class="n">pub_date</span><span class="p">)</span> <span class="o">=</span> <span class="s1">&#39;3&#39;</span><span class="p">;</span>
<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;day&#39;</span> <span class="n">FROM</span> <span class="n">pub_date</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="s1">&#39;3&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>Note this will match any record with a pub_date on the third day of the month,
such as January 3, July 3, etc.</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, datetime fields are converted to the
current time zone before filtering. This requires <a class="reference internal" href="#database-time-zone-definitions"><span class="std std-ref">time zone definitions
in the database</span></a>.</p>
</div>
<div class="section" id="s-week">
<span id="s-std:fieldlookup-week"></span><span id="week"></span><span id="std:fieldlookup-week"></span><h4><code class="docutils literal notranslate"><span class="pre">week</span></code><a class="headerlink" href="#week" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.11.</span> </div>
<p>For date and datetime fields, return the week number (1-52 or 53) according
to <a class="reference external" href="https://en.wikipedia.org/wiki/ISO-8601">ISO-8601</a>, i.e., weeks start
on a Monday and the first week starts on or before Thursday.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__week</span><span class="o">=</span><span class="mi">52</span><span class="p">)</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__week__gte</span><span class="o">=</span><span class="mi">32</span><span class="p">,</span> <span class="n">pub_date__week__lte</span><span class="o">=</span><span class="mi">38</span><span class="p">)</span>
</pre></div>
</div>
<p>(No equivalent SQL code fragment is included for this lookup because
implementation of the relevant query varies among different database engines.)</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, fields are converted to the current time
zone before filtering.</p>
</div>
<div class="section" id="s-week-day">
<span id="s-std:fieldlookup-week_day"></span><span id="week-day"></span><span id="std:fieldlookup-week_day"></span><h4><code class="docutils literal notranslate"><span class="pre">week_day</span></code><a class="headerlink" href="#week-day" title="Permalink to this headline">¶</a></h4>
<p>For date and datetime fields, a ‘day of the week’ match. Allows chaining
additional field lookups.</p>
<p>Takes an integer value representing the day of week from 1 (Sunday) to 7
(Saturday).</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__week_day</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__week_day__gte</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>(No equivalent SQL code fragment is included for this lookup because
implementation of the relevant query varies among different database engines.)</p>
<p>Note this will match any record with a <code class="docutils literal notranslate"><span class="pre">pub_date</span></code> that falls on a Monday (day
2 of the week), regardless of the month or year in which it occurs. Week days
are indexed with day 1 being Sunday and day 7 being Saturday.</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, datetime fields are converted to the
current time zone before filtering. This requires <a class="reference internal" href="#database-time-zone-definitions"><span class="std std-ref">time zone definitions
in the database</span></a>.</p>
</div>
<div class="section" id="s-time">
<span id="s-std:fieldlookup-time"></span><span id="time"></span><span id="std:fieldlookup-time"></span><h4><code class="docutils literal notranslate"><span class="pre">time</span></code><a class="headerlink" href="#time" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.11.</span> </div>
<p>For datetime fields, casts the value as time. Allows chaining additional field
lookups. Takes a <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.time" title="(in Python v3.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.time</span></code></a> value.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__time</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">time</span><span class="p">(</span><span class="mi">14</span><span class="p">,</span> <span class="mi">30</span><span class="p">))</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__time__range</span><span class="o">=</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">time</span><span class="p">(</span><span class="mi">8</span><span class="p">),</span> <span class="n">datetime</span><span class="o">.</span><span class="n">time</span><span class="p">(</span><span class="mi">17</span><span class="p">)))</span>
</pre></div>
</div>
<p>(No equivalent SQL code fragment is included for this lookup because
implementation of the relevant query varies among different database engines.)</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, fields are converted to the current time
zone before filtering.</p>
</div>
<div class="section" id="s-hour">
<span id="s-std:fieldlookup-hour"></span><span id="hour"></span><span id="std:fieldlookup-hour"></span><h4><code class="docutils literal notranslate"><span class="pre">hour</span></code><a class="headerlink" href="#hour" title="Permalink to this headline">¶</a></h4>
<p>For datetime and time fields, an exact hour match. Allows chaining additional
field lookups. Takes an integer between 0 and 23.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">timestamp__hour</span><span class="o">=</span><span class="mi">23</span><span class="p">)</span>
<span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">time__hour</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">timestamp__hour__gte</span><span class="o">=</span><span class="mi">12</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;hour&#39;</span> <span class="n">FROM</span> <span class="n">timestamp</span><span class="p">)</span> <span class="o">=</span> <span class="s1">&#39;23&#39;</span><span class="p">;</span>
<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;hour&#39;</span> <span class="n">FROM</span> <span class="n">time</span><span class="p">)</span> <span class="o">=</span> <span class="s1">&#39;5&#39;</span><span class="p">;</span>
<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;hour&#39;</span> <span class="n">FROM</span> <span class="n">timestamp</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="s1">&#39;12&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>For datetime fields, when <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, values are converted
to the current time zone before filtering.</p>
</div>
<div class="section" id="s-minute">
<span id="s-std:fieldlookup-minute"></span><span id="minute"></span><span id="std:fieldlookup-minute"></span><h4><code class="docutils literal notranslate"><span class="pre">minute</span></code><a class="headerlink" href="#minute" title="Permalink to this headline">¶</a></h4>
<p>For datetime and time fields, an exact minute match. Allows chaining additional
field lookups. Takes an integer between 0 and 59.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">timestamp__minute</span><span class="o">=</span><span class="mi">29</span><span class="p">)</span>
<span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">time__minute</span><span class="o">=</span><span class="mi">46</span><span class="p">)</span>
<span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">timestamp__minute__gte</span><span class="o">=</span><span class="mi">29</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;minute&#39;</span> <span class="n">FROM</span> <span class="n">timestamp</span><span class="p">)</span> <span class="o">=</span> <span class="s1">&#39;29&#39;</span><span class="p">;</span>
<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;minute&#39;</span> <span class="n">FROM</span> <span class="n">time</span><span class="p">)</span> <span class="o">=</span> <span class="s1">&#39;46&#39;</span><span class="p">;</span>
<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;minute&#39;</span> <span class="n">FROM</span> <span class="n">timestamp</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="s1">&#39;29&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>For datetime fields, When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, values are converted
to the current time zone before filtering.</p>
</div>
<div class="section" id="s-second">
<span id="s-std:fieldlookup-second"></span><span id="second"></span><span id="std:fieldlookup-second"></span><h4><code class="docutils literal notranslate"><span class="pre">second</span></code><a class="headerlink" href="#second" title="Permalink to this headline">¶</a></h4>
<p>For datetime and time fields, an exact second match. Allows chaining additional
field lookups. Takes an integer between 0 and 59.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">timestamp__second</span><span class="o">=</span><span class="mi">31</span><span class="p">)</span>
<span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">time__second</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">timestamp__second__gte</span><span class="o">=</span><span class="mi">31</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;second&#39;</span> <span class="n">FROM</span> <span class="n">timestamp</span><span class="p">)</span> <span class="o">=</span> <span class="s1">&#39;31&#39;</span><span class="p">;</span>
<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;second&#39;</span> <span class="n">FROM</span> <span class="n">time</span><span class="p">)</span> <span class="o">=</span> <span class="s1">&#39;2&#39;</span><span class="p">;</span>
<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">EXTRACT</span><span class="p">(</span><span class="s1">&#39;second&#39;</span> <span class="n">FROM</span> <span class="n">timestamp</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="s1">&#39;31&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>For datetime fields, when <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, values are converted
to the current time zone before filtering.</p>
</div>
<div class="section" id="s-isnull">
<span id="s-std:fieldlookup-isnull"></span><span id="isnull"></span><span id="std:fieldlookup-isnull"></span><h4><code class="docutils literal notranslate"><span class="pre">isnull</span></code><a class="headerlink" href="#isnull" title="Permalink to this headline">¶</a></h4>
<p>Takes either <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>, which correspond to SQL queries of
<code class="docutils literal notranslate"><span class="pre">IS</span> <span class="pre">NULL</span></code> and <code class="docutils literal notranslate"><span class="pre">IS</span> <span class="pre">NOT</span> <span class="pre">NULL</span></code>, respectively.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__isnull</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">pub_date</span> <span class="n">IS</span> <span class="n">NULL</span><span class="p">;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-search">
<span id="s-std:fieldlookup-search"></span><span id="search"></span><span id="std:fieldlookup-search"></span><h4><code class="docutils literal notranslate"><span class="pre">search</span></code><a class="headerlink" href="#search" title="Permalink to this headline">¶</a></h4>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 1.10: </span>See <a class="reference internal" href="../../releases/1.10.html#search-lookup-replacement"><span class="std std-ref">the 1.10 release notes</span></a> for how to
replace it.</p>
</div>
<p>A boolean full-text search, taking advantage of full-text indexing. This is
like <a class="reference internal" href="#std:fieldlookup-contains"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">contains</span></code></a> but is significantly faster due to full-text indexing.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__search</span><span class="o">=</span><span class="s2">&quot;+Django -jazz Python&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">MATCH</span><span class="p">(</span><span class="n">tablename</span><span class="p">,</span> <span class="n">headline</span><span class="p">)</span> <span class="n">AGAINST</span> <span class="p">(</span><span class="o">+</span><span class="n">Django</span> <span class="o">-</span><span class="n">jazz</span> <span class="n">Python</span> <span class="n">IN</span> <span class="n">BOOLEAN</span> <span class="n">MODE</span><span class="p">);</span>
</pre></div>
</div>
<p>Note this is only available in MySQL and requires direct manipulation of the
database to add the full-text index. By default Django uses BOOLEAN MODE for
full text searches. See the <a class="reference external" href="https://dev.mysql.com/doc/refman/en/fulltext-boolean.html">MySQL documentation</a> for additional details.</p>
</div>
<div class="section" id="s-regex">
<span id="s-std:fieldlookup-regex"></span><span id="regex"></span><span id="std:fieldlookup-regex"></span><h4><code class="docutils literal notranslate"><span class="pre">regex</span></code><a class="headerlink" href="#regex" title="Permalink to this headline">¶</a></h4>
<p>Case-sensitive regular expression match.</p>
<p>The regular expression syntax is that of the database backend in use.
In the case of SQLite, which has no built in regular expression support,
this feature is provided by a (Python) user-defined REGEXP function, and
the regular expression syntax is therefore that of Python’s <code class="docutils literal notranslate"><span class="pre">re</span></code> module.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">title__regex</span><span class="o">=</span><span class="sa">r</span><span class="s1">&#39;^(An?|The) +&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalents:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">title</span> <span class="n">REGEXP</span> <span class="n">BINARY</span> <span class="s1">&#39;^(An?|The) +&#39;</span><span class="p">;</span> <span class="o">--</span> <span class="n">MySQL</span>

<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">REGEXP_LIKE</span><span class="p">(</span><span class="n">title</span><span class="p">,</span> <span class="s1">&#39;^(An?|The) +&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">);</span> <span class="o">--</span> <span class="n">Oracle</span>

<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">title</span> <span class="o">~</span> <span class="s1">&#39;^(An?|The) +&#39;</span><span class="p">;</span> <span class="o">--</span> <span class="n">PostgreSQL</span>

<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">title</span> <span class="n">REGEXP</span> <span class="s1">&#39;^(An?|The) +&#39;</span><span class="p">;</span> <span class="o">--</span> <span class="n">SQLite</span>
</pre></div>
</div>
<p>Using raw strings (e.g., <code class="docutils literal notranslate"><span class="pre">r'foo'</span></code> instead of <code class="docutils literal notranslate"><span class="pre">'foo'</span></code>) for passing in the
regular expression syntax is recommended.</p>
</div>
<div class="section" id="s-iregex">
<span id="s-std:fieldlookup-iregex"></span><span id="iregex"></span><span id="std:fieldlookup-iregex"></span><h4><code class="docutils literal notranslate"><span class="pre">iregex</span></code><a class="headerlink" href="#iregex" title="Permalink to this headline">¶</a></h4>
<p>Case-insensitive regular expression match.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">title__iregex</span><span class="o">=</span><span class="sa">r</span><span class="s1">&#39;^(an?|the) +&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalents:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">title</span> <span class="n">REGEXP</span> <span class="s1">&#39;^(an?|the) +&#39;</span><span class="p">;</span> <span class="o">--</span> <span class="n">MySQL</span>

<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">REGEXP_LIKE</span><span class="p">(</span><span class="n">title</span><span class="p">,</span> <span class="s1">&#39;^(an?|the) +&#39;</span><span class="p">,</span> <span class="s1">&#39;i&#39;</span><span class="p">);</span> <span class="o">--</span> <span class="n">Oracle</span>

<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">title</span> <span class="o">~*</span> <span class="s1">&#39;^(an?|the) +&#39;</span><span class="p">;</span> <span class="o">--</span> <span class="n">PostgreSQL</span>

<span class="n">SELECT</span> <span class="o">...</span> <span class="n">WHERE</span> <span class="n">title</span> <span class="n">REGEXP</span> <span class="s1">&#39;(?i)^(an?|the) +&#39;</span><span class="p">;</span> <span class="o">--</span> <span class="n">SQLite</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-aggregation-functions">
<span id="s-id5"></span><span id="aggregation-functions"></span><span id="id5"></span><h3>Aggregation functions<a class="headerlink" href="#aggregation-functions" title="Permalink to this headline">¶</a></h3>
<p>Django provides the following aggregation functions in the
<code class="docutils literal notranslate"><span class="pre">django.db.models</span></code> module. For details on how to use these
aggregate functions, see <a class="reference internal" href="../../topics/db/aggregation.html"><span class="doc">the topic guide on aggregation</span></a>. See the <a class="reference internal" href="expressions.html#django.db.models.Aggregate" title="django.db.models.Aggregate"><code class="xref py py-class docutils literal notranslate"><span class="pre">Aggregate</span></code></a>
documentation to learn how to create your aggregates.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">SQLite can’t handle aggregation on date/time fields out of the box.
This is because there are no native date/time fields in SQLite and Django
currently emulates these features using a text field. Attempts to use
aggregation on date/time fields in SQLite will raise
<code class="docutils literal notranslate"><span class="pre">NotImplementedError</span></code>.</p>
</div>
<div class="admonition-note admonition">
<p class="first admonition-title">Note</p>
<p class="last">Aggregation functions return <code class="docutils literal notranslate"><span class="pre">None</span></code> when used with an empty
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>. For example, the <code class="docutils literal notranslate"><span class="pre">Sum</span></code> aggregation function returns <code class="docutils literal notranslate"><span class="pre">None</span></code>
instead of <code class="docutils literal notranslate"><span class="pre">0</span></code> if the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> contains no entries. An exception is
<code class="docutils literal notranslate"><span class="pre">Count</span></code>, which does return <code class="docutils literal notranslate"><span class="pre">0</span></code> if the <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> is empty.</p>
</div>
<p>All aggregates have the following parameters in common:</p>
<div class="section" id="s-expression">
<span id="expression"></span><h4><code class="docutils literal notranslate"><span class="pre">expression</span></code><a class="headerlink" href="#expression" title="Permalink to this headline">¶</a></h4>
<p>A string that references a field on the model, or a <a class="reference internal" href="expressions.html"><span class="doc">query expression</span></a>.</p>
</div>
<div class="section" id="s-output-field">
<span id="output-field"></span><h4><code class="docutils literal notranslate"><span class="pre">output_field</span></code><a class="headerlink" href="#output-field" title="Permalink to this headline">¶</a></h4>
<p>An optional argument that represents the <a class="reference internal" href="fields.html"><span class="doc">model field</span></a>
of the return value</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When combining multiple field types, Django can only determine the
<code class="docutils literal notranslate"><span class="pre">output_field</span></code> if all fields are of the same type. Otherwise, you
must provide the <code class="docutils literal notranslate"><span class="pre">output_field</span></code> yourself.</p>
</div>
</div>
<div class="section" id="s-id6">
<span id="id6"></span><h4><code class="docutils literal notranslate"><span class="pre">**extra</span></code><a class="headerlink" href="#id6" title="Permalink to this headline">¶</a></h4>
<p>Keyword arguments that can provide extra context for the SQL generated
by the aggregate.</p>
</div>
<div class="section" id="s-avg">
<span id="avg"></span><h4><code class="docutils literal notranslate"><span class="pre">Avg</span></code><a class="headerlink" href="#avg" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Avg">
<em class="property">class </em><code class="descname">Avg</code>(<em>expression</em>, <em>output_field=FloatField()</em>, <em>**extra</em>)<a class="reference internal" href="../../_modules/django/db/models/aggregates.html#Avg"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.Avg" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the mean value of the given expression, which must be numeric
unless you specify a different <code class="docutils literal notranslate"><span class="pre">output_field</span></code>.</p>
<ul class="simple">
<li>Default alias: <code class="docutils literal notranslate"><span class="pre">&lt;field&gt;__avg</span></code></li>
<li>Return type: <code class="docutils literal notranslate"><span class="pre">float</span></code> (or the type of whatever <code class="docutils literal notranslate"><span class="pre">output_field</span></code> is
specified)</li>
</ul>
</dd></dl>

</div>
<div class="section" id="s-id7">
<span id="id7"></span><h4><code class="docutils literal notranslate"><span class="pre">Count</span></code><a class="headerlink" href="#id7" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Count">
<em class="property">class </em><code class="descname">Count</code>(<em>expression</em>, <em>distinct=False</em>, <em>**extra</em>)<a class="reference internal" href="../../_modules/django/db/models/aggregates.html#Count"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.Count" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the number of objects that are related through the provided
expression.</p>
<ul class="simple">
<li>Default alias: <code class="docutils literal notranslate"><span class="pre">&lt;field&gt;__count</span></code></li>
<li>Return type: <code class="docutils literal notranslate"><span class="pre">int</span></code></li>
</ul>
<p>Has one optional argument:</p>
<dl class="attribute">
<dt id="django.db.models.Count.distinct">
<code class="descname">distinct</code><a class="headerlink" href="#django.db.models.Count.distinct" title="Permalink to this definition">¶</a></dt>
<dd><p>If <code class="docutils literal notranslate"><span class="pre">distinct=True</span></code>, the count will only include unique instances.
This is the SQL equivalent of <code class="docutils literal notranslate"><span class="pre">COUNT(DISTINCT</span> <span class="pre">&lt;field&gt;)</span></code>. The default
value is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-max">
<span id="max"></span><h4><code class="docutils literal notranslate"><span class="pre">Max</span></code><a class="headerlink" href="#max" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Max">
<em class="property">class </em><code class="descname">Max</code>(<em>expression</em>, <em>output_field=None</em>, <em>**extra</em>)<a class="reference internal" href="../../_modules/django/db/models/aggregates.html#Max"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.Max" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the maximum value of the given expression.</p>
<ul class="simple">
<li>Default alias: <code class="docutils literal notranslate"><span class="pre">&lt;field&gt;__max</span></code></li>
<li>Return type: same as input field, or <code class="docutils literal notranslate"><span class="pre">output_field</span></code> if supplied</li>
</ul>
</dd></dl>

</div>
<div class="section" id="s-min">
<span id="min"></span><h4><code class="docutils literal notranslate"><span class="pre">Min</span></code><a class="headerlink" href="#min" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Min">
<em class="property">class </em><code class="descname">Min</code>(<em>expression</em>, <em>output_field=None</em>, <em>**extra</em>)<a class="reference internal" href="../../_modules/django/db/models/aggregates.html#Min"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.Min" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the minimum value of the given expression.</p>
<ul class="simple">
<li>Default alias: <code class="docutils literal notranslate"><span class="pre">&lt;field&gt;__min</span></code></li>
<li>Return type: same as input field, or <code class="docutils literal notranslate"><span class="pre">output_field</span></code> if supplied</li>
</ul>
</dd></dl>

</div>
<div class="section" id="s-stddev">
<span id="stddev"></span><h4><code class="docutils literal notranslate"><span class="pre">StdDev</span></code><a class="headerlink" href="#stddev" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.StdDev">
<em class="property">class </em><code class="descname">StdDev</code>(<em>expression</em>, <em>sample=False</em>, <em>**extra</em>)<a class="reference internal" href="../../_modules/django/db/models/aggregates.html#StdDev"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.StdDev" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the standard deviation of the data in the provided expression.</p>
<ul class="simple">
<li>Default alias: <code class="docutils literal notranslate"><span class="pre">&lt;field&gt;__stddev</span></code></li>
<li>Return type: <code class="docutils literal notranslate"><span class="pre">float</span></code></li>
</ul>
<p>Has one optional argument:</p>
<dl class="attribute">
<dt id="django.db.models.StdDev.sample">
<code class="descname">sample</code><a class="headerlink" href="#django.db.models.StdDev.sample" title="Permalink to this definition">¶</a></dt>
<dd><p>By default, <code class="docutils literal notranslate"><span class="pre">StdDev</span></code> returns the population standard deviation. However,
if <code class="docutils literal notranslate"><span class="pre">sample=True</span></code>, the return value will be the sample standard deviation.</p>
</dd></dl>

<div class="admonition-sqlite admonition">
<p class="first admonition-title">SQLite</p>
<p class="last">SQLite doesn’t provide <code class="docutils literal notranslate"><span class="pre">StdDev</span></code> out of the box. An implementation
is available as an extension module for SQLite. Consult the <a class="reference external" href="https://www.sqlite.org/contrib">SQlite
documentation</a> for instructions on obtaining and installing this
extension.</p>
</div>
</dd></dl>

</div>
<div class="section" id="s-sum">
<span id="sum"></span><h4><code class="docutils literal notranslate"><span class="pre">Sum</span></code><a class="headerlink" href="#sum" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Sum">
<em class="property">class </em><code class="descname">Sum</code>(<em>expression</em>, <em>output_field=None</em>, <em>**extra</em>)<a class="reference internal" href="../../_modules/django/db/models/aggregates.html#Sum"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.Sum" title="Permalink to this definition">¶</a></dt>
<dd><p>Computes the sum of all values of the given expression.</p>
<ul class="simple">
<li>Default alias: <code class="docutils literal notranslate"><span class="pre">&lt;field&gt;__sum</span></code></li>
<li>Return type: same as input field, or <code class="docutils literal notranslate"><span class="pre">output_field</span></code> if supplied</li>
</ul>
</dd></dl>

</div>
<div class="section" id="s-variance">
<span id="variance"></span><h4><code class="docutils literal notranslate"><span class="pre">Variance</span></code><a class="headerlink" href="#variance" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Variance">
<em class="property">class </em><code class="descname">Variance</code>(<em>expression</em>, <em>sample=False</em>, <em>**extra</em>)<a class="reference internal" href="../../_modules/django/db/models/aggregates.html#Variance"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.Variance" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the variance of the data in the provided expression.</p>
<ul class="simple">
<li>Default alias: <code class="docutils literal notranslate"><span class="pre">&lt;field&gt;__variance</span></code></li>
<li>Return type: <code class="docutils literal notranslate"><span class="pre">float</span></code></li>
</ul>
<p>Has one optional argument:</p>
<dl class="attribute">
<dt id="django.db.models.Variance.sample">
<code class="descname">sample</code><a class="headerlink" href="#django.db.models.Variance.sample" title="Permalink to this definition">¶</a></dt>
<dd><p>By default, <code class="docutils literal notranslate"><span class="pre">Variance</span></code> returns the population variance. However,
if <code class="docutils literal notranslate"><span class="pre">sample=True</span></code>, the return value will be the sample variance.</p>
</dd></dl>

<div class="admonition-sqlite admonition">
<p class="first admonition-title">SQLite</p>
<p class="last">SQLite doesn’t provide <code class="docutils literal notranslate"><span class="pre">Variance</span></code> out of the box. An implementation
is available as an extension module for SQLite. Consult the <a class="reference external" href="https://www.sqlite.org/contrib">SQlite
documentation</a> for instructions on obtaining and installing this
extension.</p>
</div>
</dd></dl>

</div>
</div>
</div>
<div class="section" id="s-query-related-tools">
<span id="query-related-tools"></span><h2>Query-related tools<a class="headerlink" href="#query-related-tools" title="Permalink to this headline">¶</a></h2>
<p>This section provides reference material for query-related tools not documented
elsewhere.</p>
<div class="section" id="s-q-objects">
<span id="q-objects"></span><h3><code class="docutils literal notranslate"><span class="pre">Q()</span></code> objects<a class="headerlink" href="#q-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.models.Q">
<em class="property">class </em><code class="descname">Q</code><a class="reference internal" href="../../_modules/django/db/models/query_utils.html#Q"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.Q" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>A <code class="docutils literal notranslate"><span class="pre">Q()</span></code> object, like an <a class="reference internal" href="expressions.html#django.db.models.F" title="django.db.models.F"><code class="xref py py-class docutils literal notranslate"><span class="pre">F</span></code></a> object, encapsulates a
SQL expression in a Python object that can be used in database-related
operations.</p>
<p>In general, <code class="docutils literal notranslate"><span class="pre">Q()</span> <span class="pre">objects</span></code> make it possible to define and reuse conditions.
This permits the <a class="reference internal" href="../../topics/db/queries.html#complex-lookups-with-q"><span class="std std-ref">construction of complex database queries</span></a> using <code class="docutils literal notranslate"><span class="pre">|</span></code> (<code class="docutils literal notranslate"><span class="pre">OR</span></code>) and <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> (<code class="docutils literal notranslate"><span class="pre">AND</span></code>) operators;
in particular, it is not otherwise possible to use <code class="docutils literal notranslate"><span class="pre">OR</span></code> in <code class="docutils literal notranslate"><span class="pre">QuerySets</span></code>.</p>
</div>
<div class="section" id="s-prefetch-objects">
<span id="prefetch-objects"></span><h3><code class="docutils literal notranslate"><span class="pre">Prefetch()</span></code> objects<a class="headerlink" href="#prefetch-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.models.Prefetch">
<em class="property">class </em><code class="descname">Prefetch</code>(<em>lookup</em>, <em>queryset=None</em>, <em>to_attr=None</em>)<a class="reference internal" href="../../_modules/django/db/models/query.html#Prefetch"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.Prefetch" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>The <code class="docutils literal notranslate"><span class="pre">Prefetch()</span></code> object can be used to control the operation of
<a class="reference internal" href="#django.db.models.query.QuerySet.prefetch_related" title="django.db.models.query.QuerySet.prefetch_related"><code class="xref py py-meth docutils literal notranslate"><span class="pre">prefetch_related()</span></code></a>.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">lookup</span></code> argument describes the relations to follow and works the same
as the string based lookups passed to
<a class="reference internal" href="#django.db.models.query.QuerySet.prefetch_related" title="django.db.models.query.QuerySet.prefetch_related"><code class="xref py py-meth docutils literal notranslate"><span class="pre">prefetch_related()</span></code></a>. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="k">import</span> <span class="n">Prefetch</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;choice_set&#39;</span><span class="p">))</span><span class="o">.</span><span class="n">get</span><span class="p">()</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">&lt;QuerySet [&lt;Choice: Not much&gt;, &lt;Choice: The sky&gt;, &lt;Choice: Just hacking again&gt;]&gt;</span>
<span class="go"># This will only execute two queries regardless of the number of Question</span>
<span class="go"># and Choice objects.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;choice_set&#39;</span><span class="p">))</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">&lt;QuerySet [&lt;Question: What&#39;s up?&gt;]&gt;</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">queryset</span></code> argument supplies a base <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> for the given lookup.
This is useful to further filter down the prefetch operation, or to call
<a class="reference internal" href="#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><code class="xref py py-meth docutils literal notranslate"><span class="pre">select_related()</span></code></a> from the prefetched
relation, hence reducing the number of queries even further:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">voted_choices</span> <span class="o">=</span> <span class="n">Choice</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">votes__gt</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">voted_choices</span>
<span class="go">&lt;QuerySet [&lt;Choice: The sky&gt;]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prefetch</span> <span class="o">=</span> <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;choice_set&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">voted_choices</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="n">prefetch</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">()</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">&lt;QuerySet [&lt;Choice: The sky&gt;]&gt;</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">to_attr</span></code> argument sets the result of the prefetch operation to a custom
attribute:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">prefetch</span> <span class="o">=</span> <span class="n">Prefetch</span><span class="p">(</span><span class="s1">&#39;choice_set&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">voted_choices</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="s1">&#39;voted_choices&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="n">prefetch</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">()</span><span class="o">.</span><span class="n">voted_choices</span>
<span class="go">&lt;QuerySet [&lt;Choice: The sky&gt;]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="n">prefetch</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">()</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">&lt;QuerySet [&lt;Choice: Not much&gt;, &lt;Choice: The sky&gt;, &lt;Choice: Just hacking again&gt;]&gt;</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When using <code class="docutils literal notranslate"><span class="pre">to_attr</span></code> the prefetched result is stored in a list. This can
provide a significant speed improvement over traditional
<code class="docutils literal notranslate"><span class="pre">prefetch_related</span></code> calls which store the cached result within a
<code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> instance.</p>
</div>
</div>
<div class="section" id="s-prefetch-related-objects">
<span id="prefetch-related-objects"></span><h3><code class="docutils literal notranslate"><span class="pre">prefetch_related_objects()</span></code><a class="headerlink" href="#prefetch-related-objects" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="django.db.models.prefetch_related_objects">
<code class="descname">prefetch_related_objects</code>(<em>model_instances</em>, <em>*related_lookups</em>)<a class="reference internal" href="../../_modules/django/db/models/query.html#prefetch_related_objects"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.prefetch_related_objects" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.10.</span> </div>
<p>Prefetches the given lookups on an iterable of model instances. This is useful
in code that receives a list of model instances as opposed to a <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>;
for example, when fetching models from a cache or instantiating them manually.</p>
<p>Pass an iterable of model instances (must all be of the same class) and the
lookups or <a class="reference internal" href="#django.db.models.Prefetch" title="django.db.models.Prefetch"><code class="xref py py-class docutils literal notranslate"><span class="pre">Prefetch</span></code></a> objects you want to prefetch for. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="k">import</span> <span class="n">prefetch_related_objects</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">restaurants</span> <span class="o">=</span> <span class="n">fetch_top_restaurants_from_cache</span><span class="p">()</span>  <span class="c1"># A list of Restaurants</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prefetch_related_objects</span><span class="p">(</span><span class="n">restaurants</span><span class="p">,</span> <span class="s1">&#39;pizzas__toppings&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#"><code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> API reference</a><ul>
<li><a class="reference internal" href="#when-querysets-are-evaluated">When <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s are evaluated</a><ul>
<li><a class="reference internal" href="#pickling-querysets">Pickling <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s</a></li>
</ul>
</li>
<li><a class="reference internal" href="#queryset-api"><code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> API</a><ul>
<li><a class="reference internal" href="#methods-that-return-new-querysets">Methods that return new <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s</a><ul>
<li><a class="reference internal" href="#filter"><code class="docutils literal notranslate"><span class="pre">filter()</span></code></a></li>
<li><a class="reference internal" href="#exclude"><code class="docutils literal notranslate"><span class="pre">exclude()</span></code></a></li>
<li><a class="reference internal" href="#annotate"><code class="docutils literal notranslate"><span class="pre">annotate()</span></code></a></li>
<li><a class="reference internal" href="#order-by"><code class="docutils literal notranslate"><span class="pre">order_by()</span></code></a></li>
<li><a class="reference internal" href="#reverse"><code class="docutils literal notranslate"><span class="pre">reverse()</span></code></a></li>
<li><a class="reference internal" href="#distinct"><code class="docutils literal notranslate"><span class="pre">distinct()</span></code></a></li>
<li><a class="reference internal" href="#values"><code class="docutils literal notranslate"><span class="pre">values()</span></code></a></li>
<li><a class="reference internal" href="#values-list"><code class="docutils literal notranslate"><span class="pre">values_list()</span></code></a></li>
<li><a class="reference internal" href="#dates"><code class="docutils literal notranslate"><span class="pre">dates()</span></code></a></li>
<li><a class="reference internal" href="#datetimes"><code class="docutils literal notranslate"><span class="pre">datetimes()</span></code></a></li>
<li><a class="reference internal" href="#none"><code class="docutils literal notranslate"><span class="pre">none()</span></code></a></li>
<li><a class="reference internal" href="#all"><code class="docutils literal notranslate"><span class="pre">all()</span></code></a></li>
<li><a class="reference internal" href="#union"><code class="docutils literal notranslate"><span class="pre">union()</span></code></a></li>
<li><a class="reference internal" href="#intersection"><code class="docutils literal notranslate"><span class="pre">intersection()</span></code></a></li>
<li><a class="reference internal" href="#difference"><code class="docutils literal notranslate"><span class="pre">difference()</span></code></a></li>
<li><a class="reference internal" href="#select-related"><code class="docutils literal notranslate"><span class="pre">select_related()</span></code></a></li>
<li><a class="reference internal" href="#prefetch-related"><code class="docutils literal notranslate"><span class="pre">prefetch_related()</span></code></a></li>
<li><a class="reference internal" href="#extra"><code class="docutils literal notranslate"><span class="pre">extra()</span></code></a></li>
<li><a class="reference internal" href="#defer"><code class="docutils literal notranslate"><span class="pre">defer()</span></code></a></li>
<li><a class="reference internal" href="#only"><code class="docutils literal notranslate"><span class="pre">only()</span></code></a></li>
<li><a class="reference internal" href="#using"><code class="docutils literal notranslate"><span class="pre">using()</span></code></a></li>
<li><a class="reference internal" href="#select-for-update"><code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code></a></li>
<li><a class="reference internal" href="#raw"><code class="docutils literal notranslate"><span class="pre">raw()</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#methods-that-do-not-return-querysets">Methods that do not return <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s</a><ul>
<li><a class="reference internal" href="#get"><code class="docutils literal notranslate"><span class="pre">get()</span></code></a></li>
<li><a class="reference internal" href="#create"><code class="docutils literal notranslate"><span class="pre">create()</span></code></a></li>
<li><a class="reference internal" href="#get-or-create"><code class="docutils literal notranslate"><span class="pre">get_or_create()</span></code></a></li>
<li><a class="reference internal" href="#update-or-create"><code class="docutils literal notranslate"><span class="pre">update_or_create()</span></code></a></li>
<li><a class="reference internal" href="#bulk-create"><code class="docutils literal notranslate"><span class="pre">bulk_create()</span></code></a></li>
<li><a class="reference internal" href="#count"><code class="docutils literal notranslate"><span class="pre">count()</span></code></a></li>
<li><a class="reference internal" href="#in-bulk"><code class="docutils literal notranslate"><span class="pre">in_bulk()</span></code></a></li>
<li><a class="reference internal" href="#iterator"><code class="docutils literal notranslate"><span class="pre">iterator()</span></code></a><ul>
<li><a class="reference internal" href="#with-server-side-cursors">With server-side cursors</a></li>
<li><a class="reference internal" href="#without-server-side-cursors">Without server-side cursors</a></li>
</ul>
</li>
<li><a class="reference internal" href="#latest"><code class="docutils literal notranslate"><span class="pre">latest()</span></code></a></li>
<li><a class="reference internal" href="#earliest"><code class="docutils literal notranslate"><span class="pre">earliest()</span></code></a></li>
<li><a class="reference internal" href="#first"><code class="docutils literal notranslate"><span class="pre">first()</span></code></a></li>
<li><a class="reference internal" href="#last"><code class="docutils literal notranslate"><span class="pre">last()</span></code></a></li>
<li><a class="reference internal" href="#aggregate"><code class="docutils literal notranslate"><span class="pre">aggregate()</span></code></a></li>
<li><a class="reference internal" href="#exists"><code class="docutils literal notranslate"><span class="pre">exists()</span></code></a></li>
<li><a class="reference internal" href="#update"><code class="docutils literal notranslate"><span class="pre">update()</span></code></a></li>
<li><a class="reference internal" href="#delete"><code class="docutils literal notranslate"><span class="pre">delete()</span></code></a></li>
<li><a class="reference internal" href="#as-manager"><code class="docutils literal notranslate"><span class="pre">as_manager()</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#field-lookups"><code class="docutils literal notranslate"><span class="pre">Field</span></code> lookups</a><ul>
<li><a class="reference internal" href="#exact"><code class="docutils literal notranslate"><span class="pre">exact</span></code></a></li>
<li><a class="reference internal" href="#iexact"><code class="docutils literal notranslate"><span class="pre">iexact</span></code></a></li>
<li><a class="reference internal" href="#contains"><code class="docutils literal notranslate"><span class="pre">contains</span></code></a></li>
<li><a class="reference internal" href="#icontains"><code class="docutils literal notranslate"><span class="pre">icontains</span></code></a></li>
<li><a class="reference internal" href="#in"><code class="docutils literal notranslate"><span class="pre">in</span></code></a></li>
<li><a class="reference internal" href="#gt"><code class="docutils literal notranslate"><span class="pre">gt</span></code></a></li>
<li><a class="reference internal" href="#gte"><code class="docutils literal notranslate"><span class="pre">gte</span></code></a></li>
<li><a class="reference internal" href="#lt"><code class="docutils literal notranslate"><span class="pre">lt</span></code></a></li>
<li><a class="reference internal" href="#lte"><code class="docutils literal notranslate"><span class="pre">lte</span></code></a></li>
<li><a class="reference internal" href="#startswith"><code class="docutils literal notranslate"><span class="pre">startswith</span></code></a></li>
<li><a class="reference internal" href="#istartswith"><code class="docutils literal notranslate"><span class="pre">istartswith</span></code></a></li>
<li><a class="reference internal" href="#endswith"><code class="docutils literal notranslate"><span class="pre">endswith</span></code></a></li>
<li><a class="reference internal" href="#iendswith"><code class="docutils literal notranslate"><span class="pre">iendswith</span></code></a></li>
<li><a class="reference internal" href="#range"><code class="docutils literal notranslate"><span class="pre">range</span></code></a></li>
<li><a class="reference internal" href="#date"><code class="docutils literal notranslate"><span class="pre">date</span></code></a></li>
<li><a class="reference internal" href="#year"><code class="docutils literal notranslate"><span class="pre">year</span></code></a></li>
<li><a class="reference internal" href="#month"><code class="docutils literal notranslate"><span class="pre">month</span></code></a></li>
<li><a class="reference internal" href="#day"><code class="docutils literal notranslate"><span class="pre">day</span></code></a></li>
<li><a class="reference internal" href="#week"><code class="docutils literal notranslate"><span class="pre">week</span></code></a></li>
<li><a class="reference internal" href="#week-day"><code class="docutils literal notranslate"><span class="pre">week_day</span></code></a></li>
<li><a class="reference internal" href="#time"><code class="docutils literal notranslate"><span class="pre">time</span></code></a></li>
<li><a class="reference internal" href="#hour"><code class="docutils literal notranslate"><span class="pre">hour</span></code></a></li>
<li><a class="reference internal" href="#minute"><code class="docutils literal notranslate"><span class="pre">minute</span></code></a></li>
<li><a class="reference internal" href="#second"><code class="docutils literal notranslate"><span class="pre">second</span></code></a></li>
<li><a class="reference internal" href="#isnull"><code class="docutils literal notranslate"><span class="pre">isnull</span></code></a></li>
<li><a class="reference internal" href="#search"><code class="docutils literal notranslate"><span class="pre">search</span></code></a></li>
<li><a class="reference internal" href="#regex"><code class="docutils literal notranslate"><span class="pre">regex</span></code></a></li>
<li><a class="reference internal" href="#iregex"><code class="docutils literal notranslate"><span class="pre">iregex</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#aggregation-functions">Aggregation functions</a><ul>
<li><a class="reference internal" href="#expression"><code class="docutils literal notranslate"><span class="pre">expression</span></code></a></li>
<li><a class="reference internal" href="#output-field"><code class="docutils literal notranslate"><span class="pre">output_field</span></code></a></li>
<li><a class="reference internal" href="#id6"><code class="docutils literal notranslate"><span class="pre">**extra</span></code></a></li>
<li><a class="reference internal" href="#avg"><code class="docutils literal notranslate"><span class="pre">Avg</span></code></a></li>
<li><a class="reference internal" href="#id7"><code class="docutils literal notranslate"><span class="pre">Count</span></code></a></li>
<li><a class="reference internal" href="#max"><code class="docutils literal notranslate"><span class="pre">Max</span></code></a></li>
<li><a class="reference internal" href="#min"><code class="docutils literal notranslate"><span class="pre">Min</span></code></a></li>
<li><a class="reference internal" href="#stddev"><code class="docutils literal notranslate"><span class="pre">StdDev</span></code></a></li>
<li><a class="reference internal" href="#sum"><code class="docutils literal notranslate"><span class="pre">Sum</span></code></a></li>
<li><a class="reference internal" href="#variance"><code class="docutils literal notranslate"><span class="pre">Variance</span></code></a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#query-related-tools">Query-related tools</a><ul>
<li><a class="reference internal" href="#q-objects"><code class="docutils literal notranslate"><span class="pre">Q()</span></code> objects</a></li>
<li><a class="reference internal" href="#prefetch-objects"><code class="docutils literal notranslate"><span class="pre">Prefetch()</span></code> objects</a></li>
<li><a class="reference internal" href="#prefetch-related-objects"><code class="docutils literal notranslate"><span class="pre">prefetch_related_objects()</span></code></a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="instances.html"
                        title="previous chapter">Model instance reference</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="lookups.html"
                        title="next chapter">Lookup API reference</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/ref/models/querysets.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Jun 03, 2019</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="instances.html" title="Model instance reference">previous</a>
     |
    <a href="../index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="lookups.html" title="Lookup API reference">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>